Thymeleaf Elvis Operator Tutorial with Examples
1. Elvis Operator
Most computer programming languages support the Elvis operator. Below is the standard syntax of the Elvis operator in the Thymeleaf:
<p th:utext="${myVariable} ? ${myValue1} : ${myValue2}"></p>
- If myVariable is evaluated as true, the above code is equivalent to <p th:utext="${myValue1}"></p>.
- If myVariable is evaluated as false, the above code is equivalent to <p th:utext="${myValue2}"></p>.
Note: In Thymeleaf, a variable (Or a condition) is evaluated as false if its value is null, false, 0, "false", "off", "no". On the contrary, it is evaluated as true.
Example:
<h2 th:utext="${user} ? ${user.userName} : 'You are not logged in' }"></h2>
If you meet a code snippet like below, you can write it more concisely:
<p th:utext="${myVariable} ? ${myVariable} : ${myValue2}"></p>
<!-- Write shorter: -->
<p th:utext="${myVariable} ?: ${myValue2}"></p>
Example:
<!-- Example -->
<div th:utext="${errorMessage} ?: 'No error!' "></div>
<!-- Example -->
<div th:object="${user}">
...
<p>Age: <span th:text="*{age}?: '(no age specified)'">27</span>.</p>
</div>
Nested Elvis operator:
<span th:utext="${myVariable1} ? ${myValue1} : (${myVariable2} ? ${myValue21} : ${myValue22}) }"></span>
<!-- Other example .... -->
Thymeleaf Tutorials
- Thymeleaf Elvis Operator Tutorial with Examples
- Thymeleaf Loops Tutorial with Examples
- Thymeleaf Conditional statements: if, unless, switch
- Thymeleaf Predefined Objects Tutorial with Examples
- Thymeleaf th:class, th:classappend, th:style, th:styleappend
- Introduction to Thymeleaf
- Thymeleaf Variables Tutorial with Examples
- Thymeleaf Fragments Tutorial with Examples
- Thymeleaf Page Layouts Tutorial with Examples
- Thymeleaf th:object and Asterisk Syntax *{ }
- Thymeleaf Form Select option Example
Show More