仅当用户具有特定角色时,如何使用
th:classappend
将类附加到元素?
类似这样的:
<div th:classappend="${hasRole('EDITOR')?'glow':''}"></div>
我正在使用 Spring Boot、Spring Security 和 Thymeleaf。
我在 Thymeleaf“extras”Spring Security GitHub 页面找到了解决方案:
<div th:classappend="${#authorization.expression('hasRole(''EDITOR'')')?'glow':''}"></div>
版本说明: 由于新的安全限制,以下内容在 Thymeleaf 3.1+ 中不起作用。
您可以使用 request 变量,它指向当前的 HttpServletRequest:
<div th:classappend="${#request.isUserInRole('EDITOR')?'glow':''}"></div>
您还可以为您的角色使用课程。
Roles.java
public enum Role {
MEMBER("MEMBER"),
ADMIN("ADMIN");
public final String name;
Role(String name) {
this.name = name;
}
}
template.html
<div class="btn" th:classappend="${#authorization.expression('hasRole(''' + (T(com.mycompany.Role).MEMBER) + ''')')} ? 'btn-primary' : 'disabled'"></div>