Thymeleaf Variables: th:with Guide

In Thymeleaf, you can use the th:with attribute to define variables. This attribute allows you to define a local variable in the template that can be referenced elsewhere in the same template.

The syntax for defining a variable is as follows:
th:with=”variableName=${expression}”

The variable name is the name you want to give to the variable, and the expression is a Thymeleaf expression, which can be a string, number, object, etc. You can use this variable to perform calculations, comparisons, output, etc. in the template.

Here is an example of defining a variable using th:with.

<p th:with="name='John Doe'">Hello, [[${name}]]!</p>

In the example above, the variable name is defined as the string ‘John Doe’, and it can be referenced in the template using [[${name}]]. The output will be: Hello, John Doe!

bannerAds