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:
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:
Thymeleaf allows you to reuse declared local variables in the same attribute, for example:
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.
Local variable in JavaScript:
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.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}