Search code examples
xmlthymeleaf

How to write multiple if else null statement in XML template


I have an XML template where if a variable is true, this element is created:

<Tracking th:Val="Y"/>

If it is false this is created:

<Tracking th:Val="N"/>

If it is null, no element is created.

Currently I have this:

<th:block th:if="${tracking}">
    <Tracking th:Val="Y"/>
 </th:block>
 <th:block th:if="${!tracking}">
    <Tracking th:Val="N"/>
 </th:block>

Is there a better way to write this? I'm thinking maybe this:

<th:block th:if="${tracking != null}" >
    <Tracking th:Val="${tracking} ? 'Y' : 'N'"/>
</th:block>

Solution

  • I would represent it like this:

    <Tracking th:if="${tracking != null}" th:Val="${tracking ? 'Y' : 'N'}"/>
    

    (There is no need for the extra th:block.)