Using the data- * attribute with thimeleaf

Is it possible to set the data- * attribute with thimeleaf?

As I understood from the documentation of the thymeleaf, I tried:

<div th:data-el_id="${element.getId()}"> <!-- doesn't work --> <div data-th-el_id="${element.getId()}"> <!-- doesn't work --> 
+112
html thymeleaf
Jun 25 '14 at 14:45
source share
3 answers

Yes, th:attr for help Thymeleaf Documentation - Setting attribute values .

For your scenario, this should complete the task:

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

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

Note. If you want more than one attribute, separate the different attributes with a comma:

 <div th:attr="data-id=${element.getId()},data-name=${element.getNβ€Œβ€‹ame()}"> 
+199
Jun 26 '14 at 2:04
source share

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

 <div data:el_id="${element.getId()}"> 
+10
Jul 23. '15 at 15:20
source share

Thymeleaf 3.0 has a default attribute processor that can be used for any custom attributes, for example th:data-el_id="" becomes data-el_id="" , th:ng-app="" becomes ng-app="" and etc. No longer need for a favorite dialect of data attributes.

I prefer this solution if I want to use json as a value instead:

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

You can use (in combination with letter replacement ):

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

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

If anyone is interested, here you can find the corresponding tests of the template engine: Tests for the default attribute processor

+5
Dec 19 '18 at 13:53 on
source share



All Articles