Alexandru Severin
Alexandru Severin

Reputation: 6218

Using data-* attribute with Thymeleaf

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 -->

Upvotes: 151

Views: 127384

Answers (3)

RiZKiT
RiZKiT

Reputation: 2501

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:

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

You can use (in combination with literal substitution):

<div 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

Upvotes: 24

Aldrian
Aldrian

Reputation: 3009

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

Upvotes: 267

Adrian Ber
Adrian Ber

Reputation: 21360

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

Upvotes: 14

Related Questions