【问题标题】:Thymeleaf replace navbar with switch conditionsThymeleaf 用开关条件替换导航栏
【发布时间】:2021-09-14 19:20:51
【问题描述】:

不同角色的用户需要在网页顶部有不同的导航栏。我的 topnavs 是 th:fragments,写在单独的文件中,这部分代码工作正常。 但是当我使用 th:switch 和 th:replace 时,所有的 topnav 都会显示在网页中,而不仅仅是一个。

我一直在寻找这些问题的解决方案,但没有任何帮助:

Thymleaf switch statement with multiple case

How to use thymeleaf conditions - if - elseif - else

我尝试过的事情:

<span th:if = "${role.value} == 'role1' " th:replace = "fragments/topnav :: navbar_role1"></span>
<span th:if = "${role.value} == 'role2' " th:replace = "fragments/topnav :: navbar_role2"></span>

#2

<span th:if = "${role} == 'role1' " th:replace = "fragments/topnav :: navbar_role1"></span>
<span th:if = "${role} == 'role2' " th:replace = "fragments/topnav :: navbar_role2"></span>

#3

<span th:if = "${role} eq 'role1' " th:replace = "fragments/topnav :: navbar_role1"></span>
<span th:if = "${role} eq 'role2' " th:replace = "fragments/topnav :: navbar_role2"></span

#4

<th:block th:switch = "${role}">
    <div th:case = "${role} eq 'role1' " th:replace = "fragments/topnav :: navbar_role1"></div>
    <div th:case = "${role} eq 'role2' " th:replace = "fragments/topnav :: navbar_role2"></div>
</th:block>

在调试器中,我可以在 Java 代码中看到 String 类型的字段角色具有值 role2。它不仅显示了第二个导航栏,还显示了两个导航栏。 一定是我错过了 Thymeleaf 语法​​中的某些内容?

【问题讨论】:

    标签: thymeleaf


    【解决方案1】:

    目标片段需要位于子元素中,在这种情况下,替换才能按预期工作。

    假设我们在fragments/topnav.html 中有以下片段:

    <div th:fragment="navbar_role1">
        <div>This is navbar role 1</div>
    </div>
    <div th:fragment="navbar_role2">
        <div>This is navbar role 2</div>
    </div>
    

    那么你的主页可以如下结构:

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
        <head>
            <title>Switch Demo</title>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">        
        </head>
        <body>
            <th:block th:switch="${role}">
                <th:block th:case="'role1'">
                    <div th:replace="fragments/topnav :: navbar_role1"></div>
                </th:block>
                <th:block th:case="'role2'">
                    <div th:replace="fragments/topnav :: navbar_role2"></div>
                </th:block>
            </th:block>
        </body>
    </html>
    

    您显然可以使用 th:block 元素或其他东西,例如 &lt;div&gt; 元素,具体取决于您希望最终结构的外观。

    另请注意,使用th:switch 时不需要以下内容:

    th:case="${role} eq 'role1'" // NOT needed
    

    您可以简单地使用值本身:

    th:case="'role1'"
    

    这是在此处使用switch 语句的好处之一。

    【讨论】:

      猜你喜欢
      • 2011-12-21
      • 1970-01-01
      • 1970-01-01
      • 2017-10-14
      • 1970-01-01
      • 2020-05-04
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      相关资源
      最近更新 更多