Issue
I have a ul tag in thymeleaf and I have a li tag in it,and what I want is if one of the elements (which is amount here) is not null, show it, and what I want to show is something like the code below, which of course is wrong. How can I do this?
<li th:text="${ <th:if="ingredient.amount!=null> ingredient.amount"+
" "+ ingredient.uom.description"
</li>
Solution
If you alsways want to show a li
(amount==null or amount!=null) then use a th:block
with 2 li
elements with a th:if
-attribute where you check if the amount is null or not.
so lets say you have in your controller
model.addAttribute("ingredients",
List.of(
new Ingredient("3EL","Pepper"),
new Ingredient("500gr","Cheese"),
new Ingredient(null,"Salt")
)
);
then in your page
<th:block th:each="ingredient:${ingredients}">
<li th:if="${ingredient.amount != null}"
th:text="${ingredient.amount + ' of ' + ingredient.description}"></li>
<li th:if="${ingredient.amount == null}"
th:text="${'no need tu use ' + ingredient.description}"></li>
</th:block>
will generate
<ul>
<li>3EL of Pepper</li>
<li>500gr of Cheese</li>
<li>no need tu use Salt</li>
</ul>
if you only want to display the li
where the amount is not null then you don't need the th:block
<ul>
<li th:each="ingredient:${ingredients}"
th:if="${ingredient.amount != null}"
th:text="${ingredient.amount + ' of ' + ingredient.description}" ></li>
</ul>
Answered By - Dirk Deyne
Answer Checked By - David Goodson (JavaFixing Volunteer)