Create data-* attribute with Thymeleaf

September 29, 2019 No comments Thymeleaf Data Attribute data-*

1. Introduction

In this article, we will focus on how to create data- like attributes using Thymeleaf template engine. This kind of attributes are called the data attributes, and allow restrictive information to be exchanged between the HTML and its DOM.

2. Setting value to specific attributes

Let's say we want to add three data attributes to the div element:

  • data-id,
  • data-title,
  • data-date.

and we are using a simple object that contains values for those attributes:

class Post {
    private Long id;
    private String title;
    private Date date;

Thymeleaf comes with th:attr attribute that is use to provide a specific kind of our own attribute to the DOM element. We can use it to add our data attributes:

<div th:attr="data-id=${},data-title=${post.title},data-date=${#dates.format(, 'yyyy-MM-dd')}">

Note that in XML documents we cannot set an attribute twice in one tag, so we can't have more than one th:attr in the same HTML element. If we want more that one attribute, we must separate them by a comma.

The rendered HTML for sample values should look like the following:

<div data-id="1" data-tile="This is the title" data-date="2019-01-01"></div>

3. Conclusion

In this article, we showed how to add data attributes to the HTML element with Thymeleaf engine. Thymeleaf supports many common attributes and allows creating our own if we want to. So it is very elastic in this case.

Code used in this article can be found in our GitHub repository.

{{ message }}

{{ 'Comments are closed.' | trans }}