Working with local variables in Thymeleaf

January 16, 2020 No comments Thymeleaf Local Variables

1. Introduction

Thymeleaf is a template engine for processing XML and HTML documents. It comes with lots of features. In this article, we are going to present how to create and use local variables that improve the readability of the templates.

2. th:with attribute

In Thymeleaf local variables are these variables that are defined for a fragment of the template and are available only inside that fragment. If we want to declare a local variable we need to use th:with attribute.

Lets say we have the following template:

<div th:with="firstCustomer=${customers[0]}">
  <p>
    The name of the first customer is <span th:text="${firstCustomer.name}">John Doe</span>.
  </p>
</div>

th:with creates a local variable with name firstCustomer that holds the first customer from an array. In our example, this local variable will be available for evaluation on all the children of div element.

We can even declare several variables, just separete them with comma like in the following snipper:

<div th:with="firstCustomer=${customers[0]}, secondCustomer=${customers[1]}">
   <p>
    The name of the first customer is <span th:text="${firstCustomer.name}">Monika John</span>.
  </p>
  <p>
    But the name of the second customer is 
    <span th:text="${secondCustomer.name}">Johanna Alba</span>.
  </p>
</div>

Thymeleaf allows you to reuse declared local variables in the same attribute, for example:

<div th:with="customer=${customer.id},account=${accounts[customer]}">...</div>

This fragment will create two local variables: customer and account.

The easies way to understand how local variables works is to compare them to local variables used in JavaScript or any other programming language.

<div th:with="customer=${customers[0]}">
    <p>
        <span th:text="${customer.name}"></span>
    </p>
</div>

Local variable in JavaScript:

{
    var customer = customers[0];
    {
        {
            console.log(customer.name); // here customer is available
        }
    }
}

var a = customer.name; // error, customers is not defined

3. Conclusion

In this article, we presented how to work with local variables in Thymeleaf templates. We learned that this kind of variables will be visible only for the children of that attribute where they were created. Local variables work the same way as variables used in any programming language. We can use them to improve the readability of our template.

{{ message }}

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