java - 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>
解决方案
三元运算符是对三个操作数进行运算的运算符。
如果 的值为真,则表达式的a ? b : c
计算结果为 ,否则为。b
a
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>
推荐阅读
- wordpress - 如何从谷歌地图中隐藏评论部分
- html - 如何设置浮动元素自动填充其父元素的剩余高度(高度不固定并显示为表格)?
- postgresql - 检测包含除空格以外的特殊字符的列 - Postgresql
- r - 计算数据帧列表中的出现次数并将结果存储在 R 中的新数据帧中
- php - PHP - 文件上传不起作用
- java - 将用户输入(来自 TextField)传递给另一个类?
- mongodb - 根据条件从所有集合中删除文档
- react-redux - 使用 AgGridReact 无限滚动
- java - 如何使用构造函数注入模拟类
- mysql - Python MySQL 没有要从中获取的结果集