HTML-Hilfsfunktionen
Manchmal brauchst du Attributwerte in deinen CSS- oder JS-Dateien. Blockstudio stellt Hilfsfunktionen bereit, um Attribute als Datenattribute oder CSS-Variablen zu rendern.
Beispielblock
Stell dir einen Block mit den folgenden Attributen vor:
JSON
{
"blockstudio": {
"attributes": [
{
"id": "message",
"type": "text",
"label": "My message"
},
{
"id": "color",
"type": "color",
"label": "My color"
}
]
}
}
Datenattribute
Die Funktion bs_render_attributes rendert Attribute als Datenattribute:
PHP
PHP
<h1 <?php bs_render_attributes($a); ?>>
<?php echo $a['message']; ?>
</h1>
Twig
Twig
<h1 {{ fn('bs_render_attributes', a) }}>
{{ a.message }}
</h1>
Ausgabe:
HTML
<h1 data-message="Hello" data-color="#7C3AED">
Hello
</h1>
Attribute filtern
Übergib einen zweiten Parameter, um festzulegen, welche Attribute gerendert werden sollen:
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>
Ausgabe:
HTML
<h1 data-color="#7C3AED">
Hello
</h1>
Zurückgeben, ohne zu rendern
Verwende bs_attributes, um den String abzurufen, ohne ihn auszugeben:
PHP
<?php $attrs = bs_attributes($a); ?>
CSS-Variablen
Die Funktion bs_render_variables rendert Attribute als CSS-Variablen:
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>
Ausgabe:
HTML
<h1 style="--message: Hello; --color: #7C3AED;">
Hello
</h1>
Variablen filtern
PHP
<h1 style="<?php bs_render_variables($a, ['color']); ?>">
Ausgabe:
HTML
<h1 style="--color: #7C3AED;">
Hello
</h1>
Zurückgeben, ohne zu rendern
Verwende bs_variables, um den String abzurufen, ohne ihn auszugeben:
PHP
<?php $vars = bs_variables($a); ?>
String-Konvertierung
Beide Funktionen wandeln Attribut-IDs in kebab-case um:
| Eingabe | Ausgabe |
|---|---|
myAttribute |
my-attribute |
my_attribute |
my-attribute |
backgroundColor |
background-color |
Verwendung in CSS
CSS
.my-block h1 {
color: var(--color);
}
Verwendung in JavaScript
JavaScript
const block = document.querySelector('.my-block h1');
const color = block.dataset.color;
const message = block.dataset.message;