多案例的 Thymleaf 开关语句

2022-09-01 18:25:22

总之

我希望在百里香中具有逻辑的开关语句,一旦写入多个案例语句。

详细地

我想在百里香中实现这一点

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'"...

注意:我知道上述错误消息的原因。我所需要的只是知道一种方法来实现单个输出的多种情况的开关


答案 1

失败的原因是在第一种情况下没有有效的表达式。具体说来

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

答案 2

我今天遇到了同样的问题,其中我中使用的对象是Java枚举。我最终发现这是一个Java equals()与==的问题。在 I 有一个枚举对象,但在我的有一个 String 对象。我通过使用 Thymeleaf 字符串函数将枚举对象转换为字符串来解决它,然后一切正常。th:switchth:switchth:case

  <div th:switch="${#strings.toString(datafile.status)}">
      <td th:case="'SUCCESS'" class="table-success">SUCCESS</td>
      <td th:case="'FAILED'" class="table-danger">FAILED</td>
      <!-- default case -->
      <td th:case="*" th:text="${#strings.toString(datafile.status)}" class="table-secondary">xxx</td>
  </div>

在上面的示例中,我使用开关有条件地将 Bootstrap 样式应用于表单元格。


另一种解决方案是在 Java 代码中执行逻辑并将输出值公开为对象属性,然后在 Thymeleaf 模板中引用该属性。像这样:

public String getBootstrapTableRowClassForStatus() {
    Objects.requireNonNull(status);
    switch (status) {
        case SUCCESS:
            return "table-success";
        case FAILED:
            return "table-danger";
        case PROCESSING:
            return "table-info";
        default:
            return "table-secondary";
    }
}

然后我使用百里香:th:class

<tr th:class="${datafile.bootstrapTableRowClassForStatus}">

在我的页面上,这将根据 Java 对象中 Status 枚举的值,将 Bootstrap 颜色样式应用于我的表行。


推荐