Attributes - HTML Utilities
Sometimes it might be necessary to use the value of attributes inside your CSS or JS files. Blockstudio provides two helper functions to render the value of attributes as data attributes or CSS variables.
Let's imagine a block with the following attribute structure:
"blockstudio": { "attributes": [ { "id": "message", "type": "text", "label": "My message" }, { "id": "color", "type": "color", "label": "My color" } ] }
Copy
Data attributes
<h1 <?php bs_render_attributes($a); ?>> <?php echo $a['message']; ?> </h1>
Copy
<h1 {{ fn('bs_render_attributes', a) }}> {{ a.message }} </h1>
Copy
The bs_render_attributes
function will render the attributes as data
attributes on the element.
<h1 data-message="Hello" data-color="#7C3AED"> Hello </h1>
Copy
The bs_render_attributes
function accepts a second parameter to specify the
attributes to render. If no attributes are specified, all attributes will be
rendered.
<h1 <?php bs_render_attributes($a, ['color']); ?>> <?php echo $a['message']; ?> </h1>
Copy
<h1 {{ fn('bs_render_attributes', a, ['color']) }}> {{ a.message }} </h1>
Copy
The above example will render the following HTML:
<h1 data-color="#7C3AED"> Hello </h1>
Copy
If you don't want to render the output, simply use the bs_attributes
function.
CSS variables
Similarly, the bs_render_variables
function will render the attributes as CSS
variables on the element. This is useful if you want to use the attributes in a
CSS file.
<h1 style="<?php bs_render_variables($a); ?>"> <?php echo $a['message']; ?> </h1>
Copy
<h1 style="{{ fn('bs_render_variables', a) }}"> {{ a.message }} </h1>
Copy
<h1 style="--message: Hello; --color: #7C3AED;"> Hello </h1>
Copy
Similarly, the bs_render_variables
function accepts a second parameter to
specify the attributes to render. If no attributes are specified, all attributes
will be rendered.
<h1 style="<?php bs_render_variables($a, ['color']); ?>"> <?php echo $a['message']; ?> </h1>
Copy
<h1 style="{{ fn('bs_render_variables', a, ['color']) }}"> {{ a.message }} </h1>
Copy
The above example will render the following HTML:
<h1 style="--color: #7C3AED;"> Hello </h1>
Copy
If you don't want to render the output, simply use the bs_variables
function.
String conversion
The bs_render_attributes
and bs_render_variables
functions will convert
attribute IDs to kebab case. For example, the IDs myAttribute
or
my_attribute
will be converted to my-attribute
.