Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally closing tag in Thymeleaf

I need to conditionally close tag in my Thymeleaf template. Say, during iterating some collection of elements I have to wrap series of some of them into single <div>:

<div>...element1, element2, element3...</div>
<div>...element4...</div>
<div>...element5, element6...</div>

This could be archived if some way of conditionally tag closing would exist. But I can't obviously write </div th:if="...">. If it would be jsp I could easily write something like:

<%if (condition) {%></div><%}%>

Any ideas how to solve this issue?

EDIT To be precise, my elements aren't just strings, they are complex inner html blocks.

like image 611
Andremoniy Avatar asked Apr 20 '16 14:04

Andremoniy


People also ask

How do I add if condition in Thymeleaf?

In some situations, you want a certain snippet of the Thymeleaf Template to appear in the result if a certain condition is evaluated as true. To do this you can use the attribute th:if. Note: In Thymeleaf, A variable or an expression is evaluated as false if its value is null, false, 0, "false", "off", "no".

Which Thymeleaf construct is used to display different UI based on a condition?

Switch Statements Thymeleaf also provides a way to display content conditionally using the equivalent of a switch statement in Java: the th:switch and th:case attributes. Note that as soon as one th:case attribute is evaluated as true , every other th:case attribute in the same switch context is evaluated as false .

How do you display text in Thymeleaf?

In this case, you should use th:text . For example, Username: <p th:text=${account. username}>Username will be rendered here</p> . Note that, the text inside p tag won't be shown.

What is th if in HTML?

The th:if statement gets placed inside an HTML tag. condition represents a boolean variable provided by the controller. Alternatively, condition can be a statement that evaluates to true or false .


1 Answers

I think it's better represent the data as separate lists, as you mentioned in your previous answer.

But even for curiosity, there is an ugly workaround to achieve something similar to <%if (condition) {%></div><%}%>, as you asked.

The trick is to generate the tag as escaped text:

<th:block th:if="${openTagCondition}" th:utext="'&lt;div&gt;'" /> 

<th:block th:if="${colseTagCondition}" th:utext="'&lt;/div&gt;'" /> 

This is just out of curiosity. I do not recommend using this workaround as it's pretty unreadable, harms maintainability and you can leave unbalanced tags.

like image 173
Tobías Avatar answered Oct 04 '22 16:10

Tobías