Thymeleaf Attributes

The Thymeleaf expressions we just saw can be used inside Thymeleaf attributes like the th:text attribute. This lesson will go over the most important attributes.

Element text content

The th:text attribute will place the result of the expression inside the tag it is declared on.

For example, assuming the username variable contains “Jane”:

<div th:text="${username}">Bob</div>

will render as:

<div>Jane</div>

Element id attribute

Similarly, the th:id attribute will add an id attribute.

<div th:id="|container-${userId}|"></div>

will render (userId will be 1 here) as:

<div id="container-1"></div>

Conditional inclusion

We can choose to render a tag subject to some condition using the th:if attribute. For example:

<div th:if="${user.followerCount > 10}">You are famous</div>

will render as:

<div>You are famous</div>

only once followerCount is more than 10.

Conditional exclusion

The th:unless attribute is opposite to th:if as it renders a tag only if the condition is false. For example:

<div th:unless="${user.followerCount > 0}">You have no followers currently.</div>

will render as:

<div>You have no followers currently</div>

only once followerCount is less than 10.

Thymeleaf has no if/else statement, but we can easily achieve the same result by combining th:if with th:unless. For example, either the first or second <div> will be rendered depending on the user.FollowerCount value:

<div th:if="${user.followerCount > 0}">You have <span th:text="${user.followerCount}"></span> followers currently.</div>
<div th:unless="${user.followerCount >0}" > You have no followers currently.</div>

Iteration

While writing the first controller, we used the th:each attribute in the view. It basically allows iteration over a collection and creates as many tags as items in the collection.

<ul><li th:each="scientist : ${scientists}" th:text="${scientist.name}"></li>
</ul>

will render as:

<ul>
  <li>Marie Curie</li>
  <li>Erwin Schr dinger</li>
  <li>Max Planck</li>
</ul>

Attribute precedence

Thymeleaf operates correctly in the above example as the evaluation of th:each is followed by the th:text. This is an example of Attribute Precedence in Thymeleaf. For example, the following two code snippets will yield the same result:

Get hands-on with 1200+ tech skills courses.