Thymeleaf is a modern server-side template engine for Java-based web applications. It is highly flexible and comes with a lot of built-in features.

In this quick article, you'll learn how to set and use a local variable in Thymeleaf templates. A local variable is basically a variable that is only available within the bounds of the HTML tag it was specified on. In Thymeleaf, such a variable is defined for a specific fragment of a template, and are only available for evaluation inside that fragment.

Using th:with Attribute

The th:with attribute is provided by the Thymeleaf engine to easily declare local variables inside the templates. Let us look at the example below:

<div th:with="name=${user.name}">
    <p>
        Hey there! I'm <span th:text="${name}">Atta</span>!
    </p>
</div>

We have just declared a local variable called name using the th:with attribute that holds the name of the user. This local variable is only available for evaluation on all child nodes inside the bounds of the containing <div> tag.

You can also even declare multiple local variables using the same th:with attribute and separate them with commas:

<div th:with="name=${user.name},country=${user.country}">
    <p>
        Hey there! My name is <span th:text="${name}">Atta</span> and I am
        from <span th:text="${country}">Pakistan</span>.
    </p>
</div>

Thymeleaf also allows you to reusable declared local variables in the same attribute as shown in the following example:

<div th:with="uid=${user.id},billing=${accounts[uid]}">
    <!-- ... -->
</div>

Conclusion

In this quick article, we looked at how to set and use local variables in Thymeleaf. We can use the th:with attribute to declare local variables in Thymeleaf templates.

A local variable in Thymeleaf is only available for evaluation on all children inside the bounds of the HTML tag that declares it. Local variables work the same as the variables coming from the application context, but only within the bounds of the containing tag.

Read Next: How to use Thymeleaf with Spring Boot

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.