ui.util.attrs

Helper method to render HTML attributes from an attrs key of an arbitrary dictionary.

{%- call ui.util.call(show_example) -%} {%- raw %} {%- set kwargs = {"attrs": {"name": "action", "hello": "world"}} -%} {%- endraw %} {%- endcall %}

This function is designed for component macros. Usually macros are defined without explicit attrs parameter, and instead they accept kwargs with all additional parameters specified by user. As result, if caller adds attrs to the macro call, it ends up inside the kwargs and can be easily processed by the utility function.

Note, in Jinja2 you do not need to declare kwargs inside macro signature. Just use variable with name kwargs somewhere inside macro code and Jinja2 collect all additional arguments into it implicitly.

{%- call ui.util.call(show_example) -%} {%- raw %} {%- macro div(content) -%}
{{ content }}
{%- endmacro %} {{ div('text', attrs={"a": 1, "b": 2}) }} {%- endraw %} {%- endcall %}

The optional second argument of the function specified default values for attributes. It can be used to provide safe defalut HTML attributes but keep a possibility to override their value via user's input.

{%- call ui.util.call(show_example) -%} {%- raw %} {%- macro button(content) -%}
{{ content }}
{%- endmacro %} {{ button('click', attrs={"class": "btn-danger"}) }} {%- endraw %} {%- endcall %}

One of the features relying on other values of kwargs is attribute shortcuts. Every attribute with data-, aria-, hx-, and on prefix can be specified inside separate item of kwargs.

{%- call ui.util.call(show_example) -%} {%- raw %} {%- macro button(content) -%}
{{ content }}
{%- endmacro %} {{ button("Click me!", data={"id": "123"}, aria={"label": "Button"}, hx={"boost": "true"}, on={"click": "alert(1)"}) }} {%- endraw %} {%- endcall %}

All these shortcuts can be used together with attrs, and specific attributes will have higher precedence than attrs.

{%- call ui.util.call(show_example) -%} {%- raw %} {{ ui.util.attrs({ "attrs": {"data-a": 1, "data-b": 2}, "data": {"a": 10}, }) }} {%- endraw %} {%- endcall %}