Thymeleaf Tutorial: Chapter 9. Local Variables

  • Tutorial
Table of contents

9 Local variables


Thymeleaf calls local variables those variables that are defined for a particular 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 list page:


    ...

This prod variable will only be available within the tag. In particular:

  • It will be available for any other th: * attributes running in this tag, with lower priority than th: each (which means that they will be executed after th: each).
  • It will be available for any child tag element, such as any elements.

Thymeleaf offers you a way to declare local variables without iteration using the th: with attribute , and its syntax is like specifying attribute values:

The name of the first person is Julius Caesar.


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 tag
.

You can define several variables at the same time using the usual multiple assignment syntax:

The name of the first person is Julius Caesar.

But the name of the second person is Marcus Antonius.


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

...

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

Today is: 13 february 2011


Well, what if we want @dd MMMM yyyy @ to depend on the 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:

Today is: 13 February 2011


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

Today is: 13 February 2011


You might think: Priority? We have not talked about this yet! Well, don’t worry, because this is exactly what is discussed in the next chapter.

Also popular now: