Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 934
Faraj Farook Avatar asked Apr 12 '15 10:04

Faraj Farook


1 Answers

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>
like image 170
tmarwen Avatar answered Oct 12 '22 11:10

tmarwen