Search code examples
javahtmlspringthymeleaf

Thymeleaf "th:each" ignores "th:switch"?


First I check if the item I get the tracklist from is a CD. If that's true I want to loop over the list and create a paragraph for each entry. My problem is that I will get an error at ${item.getTrackList()} for items that aren't a CD, because they don't have an attribute "trackList". Why is the "th:each" expression ignoring the switch-case statement?

<div th:switch="${type}" th:remove="all-but-first">
    <div th:case="CD" th:each="track : ${item.getTrackList()}">
        <p th:text="${track}"></p>
    </div>
</div>

Solution

  • http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#attribute-precedence

    th:each is evaluated before th:case. You're going to have to move it lower, something like this for example:

    <div th:switch="${type}" th:remove="all-but-first">
      <th:block th:case="CD">
        <div th:each="track : ${item.trackList}">
          <p th:text="${track}"></p>
        </div>
      </th:block>
    </div>
    

    If you don't need the extra divs, something like:

    <div th:switch="${type}" th:remove="all-but-first">
      <th:block th:case="CD">
        <p th:each="track : ${item.trackList}" th:text="${track}"></p>
      </th:block>
    </div>