3

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.

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

thanks, your solution works. It's a hacky and 'hard-to-read' one, but I think we don't have anything better in Thymeleaf.
@michal.jakubeczy Another way I thought of is <th:block th:if="{$condition}"><span data-my-attr></span></th:block><th:block th:unless="${condition}"><span></span></th:block>. Less hacky but more verbose.
yes, sure that is an option too. But disadvantage is a lot of code duplicity. I was wondering why [(${expression ? 'data-my-attribute' : ''})] inside element is not working. That would be a great way to do it.
I think code duplicity can be avoided by using th:fragment. But sure, an expression you've mentioned would be an advantage. It might be a good idea to raise an issue in Thymeleaf's github repository with a request to support adding of custom "boolean attributes" conditionally.
yeah, might be a good one. Is is still maintained btw?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.