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>
CodePudding user response:
The way thymeleaf conditions work if an IF condition is false, tag and all tags inside of it will not be displayed.
so this must be what you were looking for:
<li th:if="${ingredient.amount != null}">
<ul th:text="${your.text}"></ul>
</li>
CodePudding user response:
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>