HTML-hjælpefunktioner
Nogle gange skal du bruge attributværdier i dine CSS- eller JS-filer. Blockstudio indeholder hjælpefunktioner, der renderer attributter som dataattributter eller CSS-variabler.
Eksempelblok
Forestil dig en blok med følgende attributter:
JSON
{
"blockstudio": {
"attributes": [
{
"id": "message",
"type": "text",
"label": "My message"
},
{
"id": "color",
"type": "color",
"label": "My color"
}
]
}
}
Dataattributter
Funktionen bs_render_attributes renderer attributter som dataattributter:
PHP
PHP
<h1 <?php bs_render_attributes($a); ?>>
<?php echo $a['message']; ?>
</h1>
Twig
Twig
<h1 {{ fn('bs_render_attributes', a) }}>
{{ a.message }}
</h1>
Output:
HTML
<h1 data-message="Hello" data-color="#7C3AED">
Hello
</h1>
Filtrering af attributter
Angiv en anden parameter for at vælge, hvilke attributter der skal renderes:
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>
Output:
HTML
<h1 data-color="#7C3AED">
Hello
</h1>
Returnér uden rendering
Brug bs_attributes til at hente strengen uden at skrive den ud:
PHP
<?php $attrs = bs_attributes($a); ?>
CSS-variabler
Funktionen bs_render_variables renderer attributter som CSS-variabler:
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>
Output:
HTML
<h1 style="--message: Hello; --color: #7C3AED;">
Hello
</h1>
Filtrering af variabler
PHP
<h1 style="<?php bs_render_variables($a, ['color']); ?>">
Output:
HTML
<h1 style="--color: #7C3AED;">
Hello
</h1>
Returnér uden rendering
Brug bs_variables til at hente strengen uden at skrive den ud:
PHP
<?php $vars = bs_variables($a); ?>
Strengkonvertering
Begge funktioner konverterer attribut-id’er til kebab-case:
| Input | Output |
|---|---|
myAttribute |
my-attribute |
my_attribute |
my-attribute |
backgroundColor |
background-color |
Brug i CSS
CSS
.my-block h1 {
color: var(--color);
}
Brug i JavaScript
JavaScript
const block = document.querySelector('.my-block h1');
const color = block.dataset.color;
const message = block.dataset.message;