Search code examples
thymeleaf

When do you use th:remove="tag" versus th:block?


The following two blocks would evaluate the same, so when would you use th:remove="tag" over th:block?

<th:block th:text="${myBean.value}">[value]</th:block>

versus

<span th:remove="tag" th:text="${myBean.value}">[value]</span>


Solution

  • Since they can be used interchangeably I think it is opinion based... but for readability, my opinion is:

    <th:block /> should be used for doing structural logic (th:if, th:each, etc..) and only when it's not possible on the parent tag. For example, in the case you have to contain more than one element in a loop -- e.g, a loop that produces 2 table rows for each object:

    <table>
      <th:block th:each="object: ${objects}">
        <tr>
          <td th:text="${object.data1}" />
          <td th:text="${object.data2}" />
        </tr>
        
        <tr>
          <td th:text="${object.data3}" />
          <td th:text="${object.data4}" />
        </tr>
      </th:block>
    <table>
    

    th:remove should only be used for example data that should only be rendered when viewing the file in a browser/prototyping w/o rendering the thymeleaf:

    <table>
      <th:block th:each="object: ${objects}">
        <tr>
          <td th:text="${object.data1}" />
          <td th:text="${object.data2}" />
        </tr>
        
        <tr>
          <td th:text="${object.data3}" />
          <td th:text="${object.data4}" />
        </tr>
      </th:block>
      
      <tr th:remove="all">
        <td>Mild Cinnamon</td>
        <td>1.99</td>
      </tr>
          
      <tr th:remove="all">
        <td>Other</td>
        <td>Data</td>
      </tr>
    <table>
    

    In the specific case where you want to output data/text without a tag, I prefer inline expressions. They're enabled by default in thymeleaf 3. So:

    [[${myBean.value}]] instead of <th:block th:text="${myBean.value}">[value]</th:block>