thymeleaf

Thymeleaf - Add attribute without value


In Thymeleaf I would like to generate following HTML

<span data-my-attr>
</span>

I would like to display data-my-attr conditionally, but there seems to be no way how to display or NOT to display an empty attribute conditionally.

In case of required attribute there is th:required but for custom attributes there is nothing.

I tried to use th:attr="'data-my-attr'=${value}" and value is true or false, but it does not work.


Solution

  • Let's assume condition is true when your attribute should be shown and false when it shouldn't. You can have following:

    <span data-my-attr th:attr="${condition} ? 'meaningless' : 'data-my-attr'=''"></span>
    

    Explanation:

    According to this thread when you specify the empty value for an attribute within th:attr then Thymeleaf will delete this attribute. So in above snippet:

    1. data-my-attr is added by default.
    2. The empty value is assigned to an attribute using th:attr.
    3. The name of the attribute overriden with empty value is selected accordingly to ${condition}.
    4. When ${condition} is true then data-my-attr should stay so any meaningless name (not present within the tag) should be picked.
    5. Otherwise data-my-attr should be deleted so this name is picked.

    Feels hacky but such a way of attribute removal seems working since 2012. Therefore I'd consider it stable.