How to set and use a local variable in Thymeleaf

In this article 👇

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=${}">
        Hey there! I'm <span th:text="${name}">Atta</span>!

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=${},country=${}">
        Hey there! My name is <span th:text="${name}">Atta</span> and I am
        from <span th:text="${country}">Pakistan</span>.

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

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


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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.