Faraj Farook
Faraj Farook

Reputation: 14905

Thymeleaf th:each filtered with th:if

I need to iterate and create <span> elements for each of the component in the components array which has the name of 'MATERIAL'

My code is as below

<span th:each="component : ${body.components}" 
      th:object="${component}">
        <button th:if="*{name} == 'MATERIAL'" 
                th:text="*{title}"></button>
</span>

This code works all good until this produces a set of empty <span> elements if the name is not equal to 'MATERIAL'. I don't want this empty <span> elements to get created.

I also tried the below

<span th:each="component : ${body.components}" 
      th:object="${component}"
      th:if="*{name} == 'MATERIAL'">
         <button th:text="*{title}"></button>
</span>

This results in empty output and doesn't print anything at all. Can someone please help me on this.

Upvotes: 16

Views: 29334

Answers (1)

tmarwen
tmarwen

Reputation: 16374

You should reference the iteration item property directly using a dot (.) sign instead of going through an SpEL expression evalution (*{name}) inside your html element:

<span th:each="component : ${body.components}" 
      th:object="${component}"
      th:if="${component.name} == 'MATERIAL'">
  <button th:text="*{title}"></button>
</span>

Upvotes: 25

Related Questions