Thursday, October 10, 2019

th:block tag in Thymeleaf

While designing and developing a Thymeleaf template, have you ever faced a problem of adding unnecessary HTML tag just for holding any conditional statements or an iterative statement which you won't prefer to use if you design the same page statically? Let me give you an example: using <div> blocks inside <table> for iteration purpose only, it might work but it would add an unnecessary empty HTML tag. Don't worry Thymeleaf has a solution for this type of use case. One could use Thymeleaf's provided Synthetic th:block tag. Today we would be discussing th:block tag with some example.

1. th:block tag

  • It's an element processor included in the Standard Dialects. Don't confuse this with an attribute as it is not an attribute. 
  • It is a mere attribute container that allows template developers to specify whichever attributes they want. Thymeleaf will execute these attributes and then simply make the block disappear without a trace.

2. th:block tag Implementation Examples

There are many instances where one could use th:block tag while designing the Thymeleaf templates. It would make our Thymeleaf templates more readable and helps in avoiding unnecessary empty HTML tags which are added after processing of Thymeleaf's attributes if we don't use th: block. I would be sharing the use cases where I have used it:
  • when creating iterated tables that require more than one <tr> for each element
    Disclaimer: This example reference is taken from here. I haven't used it.
      <th:block th:each="user : ${users}">
            <td th:text="${user.login}"></td>
            <td th:text="${}"></td>
            <td colspan="2" th:text="${user.address}"></td>
  • when creating the ordered / unordered list of items
       <th:block th:each="node : ${bookModel.getOrderedSubTopics()}">
         <li th:if="${node eq 'activity'}">
     <input th:id="${node.nodeId}" type="checkbox" th:value="${node.nodeId}">
      <span th:utext="${node.label}">Topic Name</span>    
          <li th:if="${node eq 'reading'}">
       <span th:utext="${node.label}">Topic Name</span>    
  • when creating a select box when dropdown items are selected or unselected conditionally
       <option value="0"></option>
       <th:block th:each="tag : ${tags}">
         <option th:text="${tag.label}" th:if="${itemTags.contains(tag)}" th:value="${tag.tagTypeLabel}" selected>name</option>
         <option th:text="${tag.label}" th:if="not ${itemTags.contains(tag)}" th:value="${tag.tagTypeLabel}">name</option>

3. Conclusion

th:block tag is a very useful tool that could be used while designing and development of Thymeleaf templates. Template developers don't have to unnecessarily complicate their template/page by adding an HTML tag for holding Thymeleaf's attributes if they don't want that HTML tag after execution in their HTML structure.  Hoping that it would help you. Happy Learning!! ☺

1 comment: