Search code examples
javathymeleaf

Using variables in thymeleaf html


I have a thymeleaf html:

<div class="xxx">
        <label for="data.name1" th:text="#{name1}" th:for="data.name1">name1</label>
</div>

and want to make a condition: if ${data.type} is equal to "TYPE_A" then use name1 but if not then instead of name1 use name2. This is my try:

<div th:with="myVariable= ${data.type} == 'TYPE_A' ? 'name1' : 'name2'">
      <div class="xxx">
        <label for="data." + $myVariable th:text="#{$myVariable}" th:for="data." + $myVariable>$myVariable</label>
      </div>
</div>

What I'm doing wrong?


Solution

  • Try This...

    <div th:with="myVariable= ${data.type eq 'TYPE_A' ? 'name1' : 'name2'}">
      <div class="xxx">
        <label th:text="#{${myVariable}}" th:for="${'data.'+myVariable}">name1</label>
      </div>