Search code examples
xmlthymeleaf

Selecting XML Elements for output in Thymeleaf


If I had a structure like this:

<tag>
<item name="groot" group="a"/>
<item name="starlord" group="a"/>
<item name="rocket" group="a"/>

<item name="thanos" group="b"/>
<item name="ronan" group="b"/>
<item name="ego" group="b"/>
</tag>

how could I make a template to select either a or b items by matching a variable?

example: selecting "group=a" because the variable is set to a

<tag>
<item name="groot" group="a"/>
<item name="starlord" group="a"/>
<item name="rocket" group="a"/>
</tag>

Question

Is it possible also to eliminate all the "group=*" attributes as well since they are only needed for use in the template?

example

<item name="groot"/>
<item name="starlord/>
<item name="rocket"/>

alternatives?

I'm new to Thymeleaf so any other suggestions to this problem are appreciated. In a normal templating engine I would enclose the grouped items within "a" and "b" blocks using instructions within comments and completely eliminate the group attributes, but my understanding is that ThymeLeaf doesn't allow processing inside of comments.

The attributes don't specifically need to be called "group", the main thing it is just something in the template to identify the group. If there is a more appropriate thymeleaf attribute then that is fine too.


Solution

  • You can have a look at th:if or, if you have multiple cases, th:switch. Short example:

    <tag th:if="${obj.someCondition}">
        <item name="groot"/>
    </tag>
    
    <tag th:if="${not obj.someCondition}">
        <item name="thanos"/>
    </tag>
    

    where obj is an object that you registered to Thymeleaf Context (can't find the apidoc for 3.0 at the moment)