【问题标题】:Multiple if else conditions in ThymeleafThymeleaf 中的多个 if else 条件
【发布时间】:2021-03-20 11:32:43
【问题描述】:
我正在尝试使用三元运算符根据多个 if 情况附加一个 css 类。
我的三元错了吗?
我收到以下错误:
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression error.
如果我在这里查找文档或其他帖子,我找不到正确的解决方案。
我的代码如下:
<table>
<tr th:each="product: ${products}">
<th th:text="${product.status}"
th:classappend="
${product.status == 0} ? class1 :
${product.status == 1} ? class2 :
${product.status == 2} ? class3 :
${product.status == 3} ? class4 : class5">
</th>
<table>
【问题讨论】:
标签:
java
spring-boot
if-statement
thymeleaf
ternary
【解决方案1】:
Ternary Operator 是一个对 三个 操作数进行操作的运算符。
如果a 的值为真,则表达式a ? b : c 的计算结果为b,否则为c。
在您的代码中:
<table>
<tr th:each="product: ${products}">
<th th:text="${product.status}"
th:classappend="
${product.status == 0} ? class1 :
${product.status == 1} ? class2 :
${product.status == 2} ? class3 :
${product.status == 3} ? class4 : class5">
</th>
<table>
在您的第一个 : 之后您有多少个操作数?或者更准确地说,冒号后面的表达是什么?
如果您有一个复合表达式,并且您的 false 候选值是另一个三元运算符,则必须让引擎解析您的复合表达式,包括其嵌套运算符,如下所示:
a ? b : c
因此,您必须将链式嵌套运算符分组为:
<table>
<tr th:each="product: ${products}">
<th th:text="${product.status}" th:classappend="
${product.status == 0} ? class1 :
(${product.status == 1} ? class2 :
(${product.status == 2} ? class3 :
(${product.status == 3} ? class4 : class5)))">
</th>
</table>
【解决方案2】:
我找到了解决办法:
将其他条件包装在 () 中
像这样:
<table>
<tr th:each="product: ${products}">
<th th:text="${product.status}"
th:classappend="
${product.status == 0} ? class1 :
(${product.status == 1} ? class2 :
(${product.status == 2} ? class3 :
(${product.status == 3} ? class4 : class5")))>
</th>
<table>