简而言之
我想在 thymeleaf 中使用 switch 语句,一旦将逻辑写入多个 case 语句。
详细
我想在 thymeleaf 中实现这个
switch(status.value){
case 'COMPLETE':
case 'INVALID':
//print exam is not active
break;
case 'NEW':
//print exam is new and active
break;
}
我当前的 thymleaf 代码因运行时错误而失败
<div th:switch="${status.value}">
<div th:case="'COMPLETE','INVALID'">
<!-- print object is not active -->
</div>
<div th:case="NEW'">
<!-- print object is new and active -->
</div>
</div>
但是上面的代码失败并报错
org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "'COMPLETE','INVALID'"...
注意:我知道上述错误消息的原因。我所需要的只是知道一种方法来为单个输出实现具有多个案例的开关
最佳答案
失败是由于您在第一种情况下没有有效的表达式。具体来说,
'COMPLETE','INVALID'
不是有效的表达式。我怀疑你想要做的是在状态为 COMPLETE 或 INVALID 时包含 div。不幸的是,我相信您将不得不单独复制这些条件的标记。让我建议以下标记:
<!-- th:block rather than unneeded div -->
<th:block th:switch="${status.value}">
<div th:case="'COMPLETE'">
<!-- print object is not active -->
</div>
<div th:case="'INVALID'">
<!-- print object is not active -->
</div>
<div th:case="'NEW'">
<!-- print object is new and active -->
</div>
</th:block>
或者,您可以求助于 th:if,在这种情况下,它实际上可能工作得更好:
<div th:if="${status.value} eq 'COMPLETE' or ${status.value} eq 'INVALID'">
<!-- print object is not active -->
</div>
<div th:if="${status.value} eq 'NEW'">
<!-- print object is new and active -->
</div>
或者更简单:
<div th:unless="${status.value} eq 'NEW'">
<!-- print object is not active -->
</div>
<div th:if="${status.value} eq 'NEW'">
<!-- print object is new and active -->
</div>
关于java - 具有多种情况的 Thymeleaf switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29657648/