HTML-hulpprogramma’s
Soms moet u attribuutwaarden gebruiken in uw bestanden voor CSS of JS. Blockstudio biedt hulpfuncties om attributen als data-attributen of CSS-variabelen te renderen.
Voorbeeldblok
Stel dat we een blok hebben met de volgende attributen:
JSON
{
"blockstudio": {
"attributes": [
{
"id": "message",
"type": "text",
"label": "My message"
},
{
"id": "color",
"type": "color",
"label": "My color"
}
]
}
}
Data-attributen
De functie bs_render_attributes rendert attributen als data-attributen:
PHP
PHP
<h1 <?php bs_render_attributes($a); ?>>
<?php echo $a['message']; ?>
</h1>
Twig
Twig
<h1 {{ fn('bs_render_attributes', a) }}>
{{ a.message }}
</h1>
Uitvoer:
HTML
<h1 data-message="Hello" data-color="#7C3AED">
Hello
</h1>
Attributen filteren
Geef een tweede parameter mee om op te geven welke attributen moeten worden gerenderd:
PHP
PHP
<h1 <?php bs_render_attributes($a, ['color']); ?>>
<?php echo $a['message']; ?>
</h1>
Twig
Twig
<h1 {{ fn('bs_render_attributes', a, ['color']) }}>
{{ a.message }}
</h1>
Uitvoer:
HTML
<h1 data-color="#7C3AED">
Hello
</h1>
Retourneren zonder renderen
Gebruik bs_attributes om de tekenreeks op te halen zonder deze weer te geven:
PHP
<?php $attrs = bs_attributes($a); ?>
CSS-variabelen
De functie bs_render_variables rendert attributen als CSS-variabelen:
PHP
PHP
<h1 style="<?php bs_render_variables($a); ?>">
<?php echo $a['message']; ?>
</h1>
Twig
Twig
<h1 style="{{ fn('bs_render_variables', a) }}">
{{ a.message }}
</h1>
Uitvoer:
HTML
<h1 style="--message: Hello; --color: #7C3AED;">
Hello
</h1>
Variabelen filteren
PHP
<h1 style="<?php bs_render_variables($a, ['color']); ?>">
Uitvoer:
HTML
<h1 style="--color: #7C3AED;">
Hello
</h1>
Retourneren zonder renderen
Gebruik bs_variables om de tekenreeks op te halen zonder deze weer te geven:
PHP
<?php $vars = bs_variables($a); ?>
Tekenreeksconversie
Beide functies zetten attribuut-ID’s om naar kebab-case:
| Invoer | Uitvoer |
|---|---|
myAttribute |
my-attribute |
my_attribute |
my-attribute |
backgroundColor |
background-color |
Gebruiken in CSS
CSS
.my-block h1 {
color: var(--color);
}
Gebruiken in JavaScript
JavaScript
const block = document.querySelector('.my-block h1');
const color = block.dataset.color;
const message = block.dataset.message;