Steve Green
Steve Green

Reputation: 79

Thymeleaf - getting locale and comparing

The below should set h1 to HOWDY as the locale is showing en_GB, but it doesn't fall into the case?

Am I doing something wrong here? Thanks

    <h1 th:text="${#locale}"></h1>
    <div th:switch="${#locale}">
        <h1 th:case="'en_GB'">HOWDY</h1>
    </div>

Upvotes: 0

Views: 612

Answers (1)

andrewJames
andrewJames

Reputation: 22032

When you use Thymeleaf's #locale, you are using a reference to a Java Locale object.

What Works?

The following works the way you expect, because it has already evaluated the Java locale object to its string representation, before evaluating each case statement:

<div th:switch="${#locale.toString()}">
    <h1 th:case="'en_GB'">HOWDY</h1>
</div>

The following also works:

<div th:switch="__${#locale}__">
    <h1 th:case="'en_GB'">HOWDY</h1>
</div>

In this case, it works because you are using the Thymeleaf preprocessor syntax __${...}__ to force Thymeleaf to evaluate #locale (to its string representation) before it evaluates the remainder of the switch statement.

Additional Explanation

Because Thymeleaf's #locale represents a Java Locale object, you can use any of Locales suitable fields and methods, such as :

<div th:text="${#locale.country}"></div>          <!-- a field -->
<div th:text="${#locale.toLanguageTag()}"></div>  <!-- a method -->

This is why only using ${#locale} in the Thymeleaf switch statement does not match the 'en_GB' string literal that you are expecting it to match: Thymeleaf is comparing an object to a string.

When you use this...

<div th:text="${#locale}"></div>

...you are again accessing the object itself. But in this case the object will use its toString() method when being rendered by Thymeleaf, before it is displayed - giving you your en_GB displayed value.

However, when you use this...

<div th:switch="${#locale}">
    <h1 th:case="'en_GB'">HOWDY</h1>
</div>

...Thymeleaf is using the locale object in the switch statement, not its string representation.

Upvotes: 2

Related Questions