javascripthtmlspring-bootthymeleafspring-thymeleaf

springBoot + Thymeleaf: comparing values in the template


I have this piece of code:

 <div th:text="${#locale}"></div>
            <div class="language-picker js-language-picker">
            <form action="" class="language-picker__form">

                <select th:id="language-picker-select" name="language-picker-select">
                    <option th:value="es" th:selected="${#locale=='es'}">Español</option>
                    <option th:value="fr" th:selected="${#locale=='fr'}">Français</option>
                    <option th:value="pt" th:selected="${#locale=='pt'}">Português</option>
                    <option th:value="en" th:selected="${#locale=='pt'}">English</option>
                </select>
            </form>

but the selected value in the select is always the first even ${#locale} has other values

also tried with:

 <select th:id="language-picker-select" name="language-picker-select">
                    <option th:value="es" th:selected="${locale=='es'}">Español</option>
                    <option th:value="fr" th:selected="${locale=='fr'}">Français</option>
                    <option th:value="pt" th:selected="${locale=='pt'}">Português</option>
                    <option th:value="en" th:selected="${locale=='en'}">English</option>
                </select>

with the same result


Solution

  • Looks like #locale isn't a string, rather it's a java.util.Locale -- and since you're comparing a String to an Object, it will always be false. This works for me:

    <form action="" class="language-picker__form" th:with="language=${#locale.language}">
        <select th:id="language-picker-select" name="language-picker-select">
            <option th:value="es" th:selected="${language=='es'}">Español</option>
            <option th:value="fr" th:selected="${language=='fr'}">Français</option>
            <option th:value="pt" th:selected="${language=='pt'}">Português</option>
            <option th:value="en" th:selected="${language=='en'}">English</option>
        </select>
    </form>