首页 > 解决方案 > thymeleaf 的默认 else 语句 if case

问题描述

我知道我可以使用th:ifand th:unlessforif-else条件 on thymeleaf。但我想知道是否有任何其他方法可以在不使用th:unless.

我有这样的条件

th:if="${not #lists.isEmpty(myList) and condition1 and condition2 and condition3}"

现在我不想在th:unless块上重复相同的条件。有没有办法在不使用的情况下做到这一点th:unless

标签: thymeleaf

解决方案


不,没有办法做到这一点th:if——它只影响一个标签。不过,还有几个更详细的选项:

  1. 根据您的条件使用th:with。例如:

    <th:block th:with="condition=${not #lists.isEmpty(myList) and condition1 and condition2 and condition3}">
        <div th:if="${condition}" />
        <div th:unless="${condition}" />
    </th:block>
    
  2. 使用th:switch. 例如:

    <th:block th:switch="${not #lists.isEmpty(myList) and condition1 and condition2 and condition3}">
      <div th:case="true" />
      <div th:case="*" />
    </th:block>
    

推荐阅读