Create data-* attribute with Thymeleaf

July 11, 2019 No comments Thymeleaf Data Attribute data-*

1. Introduction

In this article, we will focus on adding attributes with Thymeleaf template engine. Specially attributes called the data attributes, that 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 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=${post.id},data-title=${post.title},data-date=${#dates.format(post.date, 'yyyy-MM-dd')}">
</div>

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 gives the opportunity to create 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 }}