Search code examples
thymeleaf

Difference between th:with and th:if


what is the difference between th:with and th:if in thymeleaf? Do I use th:if or th:with? I am not too sure of their difference.

I have tried to search for usage of th:with but there isn't much document around.

For example,

<td>    
    <div th:with="${a given condition}">    <!--do I use th:if or th:with here?-->
        <span th:if="${}"></span>
        <span th:if="${}"></span>
    </div>
</td>

Solution

  • th:with is used to assign variables. It doesn't have anything to do with evaluating conditions, instead it's used to assign a value to a variable. The sytnax looks like this:

    <div th:with="firstPer=${persons[0]}">
    

    th:if and th:unless are used to evaluate conditions (to determine whether or not to show a block of html).

    <div th:if="${user.isAdmin()} == false">