How to create custom attribute in Thymeleaf

September 29, 2019 No comments Thymeleaf Attribute Custom

1. Introduction

Thymeleaf is a template engine for Java-based applications. The engine comes with all the necessary methods to manipulate DOM used in the presentation layer. Beside all commonly used HTML attributes, we can create our custom once.

2. Custom attributes using th:attr

You can create custom attributes using th:attr.

In the following example we add two attributes: data-customer-id and data-customer-name to a link element:

<a th:attr="data-customer-id=${somevalue}, data-customer-name=${someothervalue}">...</a>

This will be rendered to:

<a data-customer-id="somevalue" data-customer-name="someothervalue">...</a>

Note that the name of the attribute is discretionary, however to make our document compatible with HTML5 attributes should start with data-.

In order to append a conditional attribute, you put the condition on the attribute's value, like in the following example:

<div th:attrappend="data-path=${slug != null}?@{/user/__${slug}__}">

If slug is null, the previous statement will evaluate to:

<div>

If slug is not null (value set to my-slug), the statement evaluates to:

<div data-path="/user/my-slug">

3. Conclusion

In this article, we showcased how to create custom attributes in Thymeleaf. To extend the knowledge about attributes we also presented how to add attributes conditionally. Every web developer knows that attributes in HTML documents are extremely helpful and commonly used for storing important information about presented data.

{{ message }}

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