using data-* attribute with thymeleaf

HtmlThymeleaf

Html Problem Overview


Can I set data-* attribute with thymeleaf?

As I understood from thymeleaf documentation I tried:

<div th:data-el_id="${element.getId()}"> <!-- doesn't work -->

<div data-th-el_id="${element.getId()}"> <!-- doesn't work -->

Html Solutions


Solution 1 - Html

Yes, th:attr to the rescue Thymeleaf documentation - Setting attribute values.

For your scenario, this should do the job:

<div th:attr="data-el_id=${element.getId()}">
      

XML rules do not allow you to set an attribute twice in a tag, so you can't have more than one th:attr in the same element.

Note: If you want more that one attribute, separate the different attributes by comma:

<div th:attr="data-id=${element.getId()},data-name=${element.getN‌​ame()}"> 

Solution 2 - Html

Or you can use this Thymeleaf dialect https://github.com/mxab/thymeleaf-extras-data-attribute and you'll be able do

<div data:el_id="${element.getId()}">
       

Solution 3 - Html

With Thymeleaf 3.0 there is the Default Attribute Processor which can be used for any kind of custom attributes, e.g. th:data-el_id="" becomes data-el_id="", th:ng-app="" becomes ng-app="" and so on. There is no need for the beloved data attribute dialect anymore.

This solution I prefer, if I want to use json as the value, instead of:

th:attr="data-foobar='{&quot;foo&quot:'+${bar}+'}'"

You can use (in combination with literal substitution):

th:data-foobar='|{"foo":${bar}}|'

Update: If you don't like the th namespace, you can also use HTML5 friendly attribute and element names like data-th-data-foobar="".

If someone is interested, related template engine tests can be found here: Tests for Default Attribute Processor

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexandru SeverinView Question on Stackoverflow
Solution 1 - HtmlAldrianView Answer on Stackoverflow
Solution 2 - HtmlAdrian BerView Answer on Stackoverflow
Solution 3 - HtmlRiZKiTView Answer on Stackoverflow