using data-* attribute with thymeleaf

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()}">

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


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()}"> 

Tags:

Html

Thymeleaf