Search code examples
springspring-bootthymeleaf

How to remove tag span, space, new line character in Thymeleaf conditional code block?


I am using Spring Boot 2.1.5.RELEASE, Thymeleaf 3.0.11.RELEASE (thymeleaf-3.0.11.RELEASE.jar), Thymeleaf Spring 3.0.11.RELEASE (thymeleaf-spring5-3.0.11.RELEASE.jar)

code snippet

<tr th:each="employee : ${employeeList}">
    <td th:text="${employee.order}"></td>
    <td th:text="${employee.age}"></td>
    <td th:switch="${employee.level}">
        <span th:case="0">Junior</span>
        <span th:case="1">Senior</span>
        <span th:case="2">Expert</span>
    </td>
    <td th:text="${employee.activeStatus}"></td>
</tr>

For sorting in data-grid by JavaScript, I need remove <span></span> tag pairs. For example, if an employee has level = 2. This time, Thymeleaf will render

<td><span>Expert<span></td>

I hope it become to

<td>Expert</td>

(without <span> tag). How to to this?

I also try

<tr th:each="employee : ${employeeList}">
    <td th:text="${employee.order}"></td>
    <td th:text="${employee.age}"></td>
    <td th:switch="${employee.level}">
        <th:block th:case="'0'">Junior</th:block>
        <th:block th:case="'1'">Senior</th:block>
        <th:block th:case="'2'">Expert</th:block>
    </td>
    <td th:text="${employee.activeStatus}"></td>
</tr>

But It generate unwanted character

<td>


Expert
</td>

(Has new line or space before text, It is not wanted result)


Solution

  • The answer is, you shouldn't care about the extra spaces & newlines. HTML ignores those spaces when rendering, and so it shouldn't matter to you -- and there is no way to get rid of them short of formatting hacks.

    If you really want to get rid of the spaces you could:

    1. Put the switch on one line.

      <tr th:each="employee : ${employeeList}">
          <td th:text="${employee.order}"></td>
          <td th:text="${employee.age}"></td>
          <td th:switch="${employee.level}"><th:block th:case="'0'">Junior</th:block><th:block th:case="'1'">Senior</th:block><th:block th:case="'2'">Expert</th:block></td>
          <td th:text="${employee.activeStatus}"></td>
      </tr>
      
    2. Create a Map<String, String> levelToDescription, put it on the model, and use that instead of a switch statement.

      <tr th:each="employee : ${employeeList}">
          <td th:text="${employee.order}" />
          <td th:text="${employee.age}" />
          <td th:text="${levelToDescription[employee.level]}" />
          <td th:text="${employee.activeStatus}" />
      </tr>
      

    Etc...