HTML Utilities
A volte è necessario usare i valori degli attributi nei file CSS o JS. Blockstudio fornisce funzioni helper per renderizzare gli attributi come attributi data o variabili CSS.
Blocco di esempio
Immaginiamo un blocco con i seguenti attributi:
JSON
{
"blockstudio": {
"attributes": [
{
"id": "message",
"type": "text",
"label": "My message"
},
{
"id": "color",
"type": "color",
"label": "My color"
}
]
}
}
Attributi data
La funzione bs_render_attributes renderizza gli attributi come attributi data:
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>
Filtrare gli attributi
Passate un secondo parametro per specificare quali attributi renderizzare:
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>
Restituire senza renderizzare
Usate bs_attributes per ottenere la stringa senza stamparla:
PHP
<?php $attrs = bs_attributes($a); ?>
Variabili CSS
La funzione bs_render_variables renderizza gli attributi come variabili CSS:
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>
Filtrare le variabili
PHP
<h1 style="<?php bs_render_variables($a, ['color']); ?>">
Output:
HTML
<h1 style="--color: #7C3AED;">
Hello
</h1>
Restituire senza renderizzare
Usate bs_variables per ottenere la stringa senza stamparla:
PHP
<?php $vars = bs_variables($a); ?>
Conversione in stringa
Entrambe le funzioni convertono gli ID degli attributi in kebab-case:
| Input | Output |
|---|---|
myAttribute |
my-attribute |
my_attribute |
my-attribute |
backgroundColor |
background-color |
Uso in CSS
CSS
.my-block h1 {
color: var(--color);
}
Uso in JavaScript
JavaScript
const block = document.querySelector('.my-block h1');
const color = block.dataset.color;
const message = block.dataset.message;