0

This is probably an easy question but I can't seem to think of an answer to it.

I have this simple Thymeleaf code:

<ul data-th-switch="${someVar}">
    <li data-th-case="${gt 6}">someVar is greater than 6.</li>
    <li data-th-case="*">Default case.</li>
</ul>

I get an error on data-th-case="${gt 6}". Is there a way to do this in Thymeleaf?

Thanks in advance.

ExplodingTiger
  • 327
  • 2
  • 6
  • 18

1 Answers1

1

The syntax is wrong indeed. Details.

A correct syntax one be "${someVar} gt 6" but of course, it will not work correctly, although the template will render. That is because ${someVar} evaluates to 12 (for example) while ${someVar} gt 6 evaluates to true. These are not equal.

If you enable the ThyemeLeaf trace you will see how thymeleaf will interpret this:

o.t.s.expression.GreaterThanExpression   : Evaluating GREATER THAN expression: "${someVar} > 6". Left is "12", right is "6". Result is "true"
o.t.s.expression.EqualsExpression        : Evaluating EQUALS expression: "${someVar} == (${someVar} > 6)". Left is "12", right is "true". Result is "false"

Depending on the logic which you want to implement you may come to very different solutions - e.g. from putting a gadget in your model to implementing if-else logic. Check this question for some more ideas.

Community
  • 1
  • 1
Lachezar Balev
  • 11,498
  • 9
  • 49
  • 72
  • Thanks for the input, @Lachezar Balev. I did indeed end up implementing some if-else blocks in order to solve this. I was actually migrating a JSP file to Thymeleaf and I got stuck on a tag. Surprised Thymeleaf doesn't have a similar functionality. In any case, you're absolutely right - I'm marking this as the answer. – ExplodingTiger Jan 15 '17 at 08:13