如果用户具有特定角色,如何附加CSS类?

问题描述 投票:0回答:3

仅当用户具有特定角色时,如何使用

th:classappend
将类附加到元素?

类似这样的:

<div th:classappend="${hasRole('EDITOR')?'glow':''}"></div>

我正在使用 Spring Boot、Spring Security 和 Thymeleaf。

spring-mvc spring-boot spring-security authorization thymeleaf
3个回答
2
投票

我在 Thymeleaf“extras”Spring Security GitHub 页面找到了解决方案:

<div th:classappend="${#authorization.expression('hasRole(''EDITOR'')')?'glow':''}"></div>

1
投票

版本说明: 由于新的安全限制,以下内容在 Thymeleaf 3.1+ 中不起作用。

您可以使用 request 变量,它指向当前的 HttpServletRequest:

<div th:classappend="${#request.isUserInRole('EDITOR')?'glow':''}"></div>

0
投票

您还可以为您的角色使用课程。

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>
© www.soinside.com 2019 - 2024. All rights reserved.