hasRole 检查不适用于 th:replace

hasRole check doesnt work with th:replace

我无法让 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 代码中的某些内容,但无法找出具体内容。 感谢您的帮助

也许你可以这样拆分:

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

请注意,由于 th:replaceattribute precedence 更高,因此不能通过将 <th:block><div> 组合来完成。

看起来 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>