Home > OS >  Why if-else condition not working in thymeleaf
Why if-else condition not working in thymeleaf

Time:02-14

I want display label name based on condtion using Thymeleaf, like if employee gender is 'F' then it should be display Female otherwise it should be display Male. Here down is issue which always displaying else condition.

        <center>
            <!-- IF -->
            <span th:if="${employee.gender == 'F'}">Female</span>
            <!-- ELSE -->
            <span th:unless="${employee.gender == 'F'}">Male</span>
        </center>

CodePudding user response:

To compare with an enum constant try this:

<center>
    <th:block th:if="${user.gender == T(name.now).M}">
        <span>Female</span>
    </th:block>
    
    <th:block th:unless="${user.gender == T(name.now).M}">
        <span>Male</span>
    </th:block>
</center>

CodePudding user response:

You check against 'F' in both cases. Please change it to 'M' for the unless expression.

<center>
   <!-- IF -->
    <span th:if="${employee.gender == 'F'}">Female</span>
   <!-- ELSE -->
    <span th:unless="${employee.gender == 'M'}">Male</span>
</center>

CodePudding user response:

Could you please try the following code, which is an inline evaluation form. Since you have 2 options (Male or Female) you can easily check for one option and then decide.

<center>
   <span th:text="${employee.gender == 'F'} ?  'Female' : 'Male'">Female</span>
</center>
  • Related