java - 具有多种情况的 Thymeleaf switch 语句

标签 java spring-boot thymeleaf

简而言之

我想在 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/

相关文章:

java - 如何获取同时包含JSON对象和数组的JSON数据

java - Hibernate/Spring框架: path of the database in a configuration file

java - Spring Web Flow 空白绑定(bind)应该为 null,而不是空字符串

java - 在集成测试之前运行主 springboot 应用程序

java - Spring Boot 数据未从事件监听器中保存

javascript - 我怎样才能用 thymeleaf 和 spring 4 mvc 从表中发布帖子?

html - 添加左侧导航栏

java - 使用 Rhino 的 Javascript 解析器,如何获取注释?

java - 通用使用 2 个相同的类但来自不同的包

java - 跨源servlet理论问题