首页 > 解决方案 > Thymeleaf 中的多个 if else 条件

问题描述

我正在尝试使用三元运算符根据多个 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>

标签: javaspring-bootif-statementthymeleafternary

解决方案


三元运算符是对三个操作数进行运算的运算符。

如果 的值为真,则表达式的a ? b : c计算结果为 ,否则为。bac

在您的代码中:

<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>

推荐阅读