【问题标题】:hasRole check doesnt work with th:replacehasRole 检查不适用于 th:replace
【发布时间】:2022-01-10 13:33:00
【问题描述】:

我无法让 th:replace 工作,这是我的百里香叶:

<div th:replace="${#authorization.expression('hasRole(''ROLE'')') ? 'fragments/first :: content(content=${content})' : 'fragments/second :: content(content=${content})'}"></div>

如果我转到此页面,我会收到此错误:

Error resolving template [${#authorization.expression('hasRole(''ROLE'')') ? 'fragments/upgradeblock], template might not exist or might not be accessible by any of the configured Template Resolvers (template: "fragments/first" - line 36, col 34)

我认为我必须更改 Thymeleaf 代码中的某些内容,但无法找出是什么。 谢谢你的帮助

【问题讨论】:

    标签: spring-boot spring-security thymeleaf


    【解决方案1】:

    似乎correct syntax 应该是这样的:

    <div th:replace="${#authorization.expression('hasRole(''ROLE'')')} ? ~{fragments/first :: content(content=${content})} : ~{fragments/second :: content(content=${content})}"></div>
    

    更进一步,这个syntax 也为我工作:

    <div th:replace="~{${'fragments/' + (#authorization.expression('hasRole(''ROLE'')') ? 'first' : 'second')} :: content(content=${content})}"></div>
    

    【讨论】:

    • 就是这样!非常感谢您的帮助!
    【解决方案2】:

    也许你可以这样拆分:

    <th:block th:if="${#authorization.expression('hasRole(''ROLE'')')}"> 
      <div th:replace="fragments/first :: content(content=${content})"></div>
    </th:block>
    
    <th:block th:unless="${#authorization.expression('hasRole(''ROLE'')')}"> 
      <div th:replace="fragments/second :: content(content=${content})"></div>
    </th:block>
    

    请注意,由于attribute precedenceth:replace 更高,因此无法将&lt;th:block&gt;&lt;div&gt; 组合在一起。

    【讨论】:

    • th:replaceattribute precedenceth:if/th:unless 更高——所以你必须这样做,但这个想法应该可行。 &lt;th:block th:if="${#authorization.expression('hasRole(''ROLE'')')}"&gt;&lt;div th:replace="fragments/first :: content(content=${content})"&gt;&lt;/div&gt;&lt;/th:block&gt;
    • 感谢您的两位 cmets,只是这是我试图避免的事情。我现在有 2 个 div,一个用于 !hasRole,一个用于 hasRole。我的想法是如果我可以使用三元运算符,我不需要两个 div。
    • 感谢@Metroids 的评论!我用你的信息更新了我的答案。
    猜你喜欢
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2013-11-24
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 2014-01-09
    相关资源
    最近更新 更多