Search code examples
spring-bootthymeleaf

Thymeleaf - Is there a simple way to make radio checked based on condition


I'm using spring boot + thymeleaf and I try create list of checkboxes with minimum code. Checkboxes present the all user roles (USER, ADMIN) and it must be checked if a user has such role.

So, at first, I tried to make it like this:

<p>
    <input th:type="radio" th:value="${role}"
          th:checked="${user.getRoles().contains(role)} ? 'checked' : 'unchecked'" />
    <th:block th:utext="${role}"/>
</p>

but it's didn't work.

Then I made it like this:

<th:block th:each="role : ${userRoles}">
    <p>
        <th:block th:if="${user.getRoles().contains(role)}">
            <input th:type="radio" checked />
        </th:block>
        <th:block th:if="${!user.getRoles().contains(role)}">
            <input th:type="radio"/>
        </th:block>
        <th:block th:utext="${role}"/>
    </p>
</th:block>

And this is work, but is there a simple way to do this like my the first try? Thanks!


Solution

  • The <input> elements of type radio support common attribute checked. This is the Boolean attribute which accepts true and false as the possible values. Said that your Thymeleaf condition can be placed directly into the value of this attribute as follow ...

    <p>
        <input th:type="radio" th:value="${role}"
          th:checked="${user.getRoles().contains(role)}" />
        <th:block th:utext="${role}"/>
    </p>
    

    More on Thymeleaf Fixed-value boolean attributes