Thymeleaf th: each is filtered with th: if

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

My code is below

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

This code works well until it creates a set of empty <span> elements if name not equal to 'MATERIAL' . I do not want these empty <span> elements to be created.

I also tried below

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

The result is an empty output and does not print anything. Can someone please help me with this.

+6
source share
1 answer

You should reference the property of the iteration element directly using the dot sign ( . ) Instead of checking the SpEL ( *{name} ) expression inside your html element:

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

Source: https://habr.com/ru/post/985011/


All Articles