📜 ⬆️ ⬇️

Thymeleaf Tutorial: Chapter 9. Local Variables

Table of contents

9 Local Variables


Thymeleaf calls local variables those variables that are defined for a specific fragment of the template and are only available for execution inside this fragment.

An example that we have already seen is the prod variable on our product listing page:

<tr th:each="prod : ${prods}"> ... </tr> 

This prod variable will only be available within the <tr> tag. In particular:
')

Thymeleaf offers you a way to declare local variables without iteration using the th: with attribute, and its syntax is as an indication of attribute values:

 <div th:with="firstPer=${persons[0]}"> <p> The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>. </p> </div> 

When th: with is processed, this firstPer variable is created as a local variable and added to the list of variables, based on the context, so that it is available for execution along with any other variables declared in the context, but only within the containing <div> tag.

You can define several variables at once using the usual multi-assignment syntax:

 <div th:with="firstPer=${persons[0]},secondPer=${persons[1]}"> <p> The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>. </p> <p> But the name of the second person is <span th:text="${secondPer.name}">Marcus Antonius</span>. </p> </div> 

The th: with attribute allows you to reuse variables defined in the same attribute:

 <div th:with="company=${user.company + ' Co.'},account=${accounts[company]}">...</div> 

Let's use this on our Grocery homepage! Remember the code we wrote to display a formatted date?

 <p> Today is: <span th:text="${#calendars.format(today,'dd MMMM yyyy')}">13 february 2011</span> </p> 

But what if we want @dd MMMM yyyy @ to depend on locale? For example, we could add the following message to our home_en.properties:

 date.format=MMMM dd'','' yyyy 

... and the equivalent of home_es.properties

 date.format=dd ''de'' MMMM'','' yyyy 

Now let's use th: with to get the localized date format in a variable, and then use it in our th: text expression:

 <p th:with="df=#{date.format}"> Today is: <span th:text="${#calendars.format(today,df)}">13 February 2011</span> </p> 

It was clean and easy. In fact, given the fact that th: with has a higher priority than th: text , we could solve all this in a span tag:

 <p> Today is: <span th:with="df=#{date.format}" th:text="${#calendars.format(today,df)}">13 February 2011</span> </p> 

You might think: Priority? We haven't talked about this yet! Well, don't worry, because this is exactly what the next chapter is about.

Source: https://habr.com/ru/post/351852/


All Articles