Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf: Switch statement for a language selector

I'm implementing a language selector with Thymeleaf for a Spring Boot project, but I can't get the variable ${#ctx.locale} working in the case statements. It takes always the default one ("*").

<li class="nav-item dropdown">
<a class="nav dropdown-toggle"
   id="languages" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

        <i class="material-icons">language</i>

        <div th:switch="${#ctx.locale}">
            <p th:case="en">English</p>
            <p th:case="es">Español</p>
            <p th:case="ca">Català</p>
            <p th:case="*">English</p>
        </div>
</a>
<div class="dropdown-menu" aria-labelledby="languages">
    <a class="dropdown-item" th:href="@{?lang=en}">English</a>
    <a class="dropdown-item" th:href="@{?lang=es}">Español</a>
    <a class="dropdown-item" th:href="@{?lang=ca}">Català</a>
</div>

In fact, I just need the language name. Thank you.

like image 429
Aleix Alcover Avatar asked Feb 05 '23 22:02

Aleix Alcover


1 Answers

The explanation is here: thymeleaf-compare-locale-expression-object-with-string

In your code change th:switch="${#ctx.locale}" to th:switch="__${#locale.language}__"

<div th:switch="__${#locale.language}__">
    <p th:case="en">English</p>
    <p th:case="es">Español</p>
    <p th:case="ca">Català</p>
    <p th:case="*">English</p>
</div>
like image 171
Francisco Pérez Avatar answered Feb 11 '23 18:02

Francisco Pérez