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:
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:
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:
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.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}