Java 带有多个 case 的 Thymleaf switch 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29657648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Thymleaf switch statement with multiple case
提问by Faraj Farook
In Short
简而言之
I want to have switch statement in thymeleaf with logic once written to multiple case statements.
我想在 thymeleaf 中使用 switch 语句,一旦将逻辑写入多个 case 语句。
In detail
详细
I want to implement this in the thymeleaf
我想在百里香叶中实现这个
switch(status.value){
case 'COMPLETE':
case 'INVALID':
//print exam is not active
break;
case 'NEW':
//print exam is new and active
break;
}
My current thymleaf code which fails with runtime error
我当前的 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>
But the above code fails with error
但是上面的代码失败并报错
org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "'COMPLETE','INVALID'"...
org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "'COMPLETE','INVALID'"...
Note: I know the reason for this above error message. All I need is to know a way to implement switch with multiple cases for a single output
注意:我知道上述错误消息的原因。我所需要的只是知道一种为单个输出实现多情况切换的方法
采纳答案by pens-fan-69
The failure is due to the fact that you don't have a valid expression in the first case. Specifically,
失败是由于您在第一种情况下没有有效的表达式。具体来说,
'COMPLETE','INVALID'
is not a valid expression. I suspect that what you are trying to do is include the div if the status is COMPLETE or INVALID. Unfortunately, I believe you will have to duplicate the markup for those conditions individually. Let me suggest the following markup:
不是有效的表达式。如果状态为 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>
Alternatively you could resort to th:if which might actually work better in this case:
或者,您可以求助于 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>
Or even more simply:
或者更简单:
<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>