Search code examples
javaspring-bootthymeleaf

Don't process the each case when if case is true in thymeleaf


I am working on a spring boot application. I have the following thymeleaf block:

<Produkt th:if="${visibility}" th:each="user: ${userList.myList}">
    <Name th:text="${user.name}"/>
</Produkt>

I have the following java code:

@Test
public void myTest() {
    Context context = new Context();
    Map<String, List<Map<String, String>>> userValuesList = new HashMap<>();
    boolean visibility = getVisibility();
    if (visibility) {
        List<Map<String, String>> vv = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        map.put("name", "filip");
        vv.add(map);
        Map<String, String> map2 = new HashMap<>();
        map2.put("name", "test");
        vv.add(map2);
        userValuesList.put("myList", vv);
    }
    context.setVariable("visibility", visibility);
    context.setVariable("userList", userValuesList);
    springTemplateEngine.process("test.xml", context);
}

Since I am adding this myList only when visibility is true, I am getting the following error:

Exception evaluating SpringEL expression: "userList.myList"

My question is is it possible for this userList.myList to be processed by the springTemplateEngine only if visibility is true ?

The end result that I want to achieve is:

<Produkt>
    <Name>filip</Name>
</Produkt>

<Produkt>
    <Name>test</Name>
</Produkt>

and in case if visbility is false, this whole Produkt tag to be gone.


Solution

  • Thymeleaf th:each attribute has higher precedence than th:if attribute. All Thymeleaf attributes define a numeric precedence, which establishes the order in which they are executed in the tag. To achieve your requirements just use th:if attribute in it's own tag which will be a container to the tag with th:each attribute ...

    <div th:if="${visibility}">
        <Produkt th:each="user: ${userList.myList}">
            <Name th:text="${user.name}"/>
        </Produkt>
    </div>