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.
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:
data-my-attr is added by default.th:attr.${condition}.${condition} is true then data-my-attr should stay so any meaningless name (not present within the tag) should be picked.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.