Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf - Add attribute without value

Tags:

thymeleaf

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.

like image 629
michal.jakubeczy Avatar asked Aug 06 '26 15:08

michal.jakubeczy


1 Answers

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.

like image 90
Jakub Ch. Avatar answered Aug 10 '26 12:08

Jakub Ch.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!