HTML-apuohjelmat
Joskus attribuuttiarvoja on käytettävä CSS- tai JS-tiedostoissa. Blockstudio tarjoaa apufunktioita, joilla attribuutit voi renderöidä data-attribuutteina tai CSS-muuttujina.
Esimerkkilohko
Kuvitellaan lohko, jolla on seuraavat attribuutit:
JSON
{
"blockstudio": {
"attributes": [
{
"id": "message",
"type": "text",
"label": "My message"
},
{
"id": "color",
"type": "color",
"label": "My color"
}
]
}
}
Data-attribuutit
Funktio bs_render_attributes renderöi attribuutit data-attribuutteina:
PHP
PHP
<h1 <?php bs_render_attributes($a); ?>>
<?php echo $a['message']; ?>
</h1>
Twig
Twig
<h1 {{ fn('bs_render_attributes', a) }}>
{{ a.message }}
</h1>
Tuloste:
HTML
<h1 data-message="Hello" data-color="#7C3AED">
Hello
</h1>
Attribuuttien suodatus
Määritä renderöitävät attribuutit toisella parametrilla:
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>
Tuloste:
HTML
<h1 data-color="#7C3AED">
Hello
</h1>
Palautus ilman renderöintiä
Käytä funktiota bs_attributes saadaksesi merkkijonon ilman tulostamista:
PHP
<?php $attrs = bs_attributes($a); ?>
CSS-muuttujat
Funktio bs_render_variables renderöi attribuutit CSS-muuttujina:
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>
Tuloste:
HTML
<h1 style="--message: Hello; --color: #7C3AED;">
Hello
</h1>
Muuttujien suodatus
PHP
<h1 style="<?php bs_render_variables($a, ['color']); ?>">
Tuloste:
HTML
<h1 style="--color: #7C3AED;">
Hello
</h1>
Palautus ilman renderöintiä
Käytä funktiota bs_variables saadaksesi merkkijonon ilman tulostamista:
PHP
<?php $vars = bs_variables($a); ?>
Merkkijonoksi muuntaminen
Molemmat funktiot muuntavat attribuuttien tunnisteet kebab-case-muotoon:
| Syöte | Tuloste |
|---|---|
myAttribute |
my-attribute |
my_attribute |
my-attribute |
backgroundColor |
background-color |
Käyttö: CSS
CSS
.my-block h1 {
color: var(--color);
}
Käyttö: JavaScript
JavaScript
const block = document.querySelector('.my-block h1');
const color = block.dataset.color;
const message = block.dataset.message;