向grails中的所有视图添加变量

2024-04-25

我试图在所有视图中为当前用户(POJO)设置一个变量,以便我可以获得用户名之类的信息并检查他们在每个视图(包括默认布局)上的角色。如何在 grails 中设置某些内容(例如 currentUser),以便在每个 grails 视图中都可以访问它,如下所示:

<div>${currentUser.name}</div>

或者像这样:

<g:if test="${currentUser.admin}">ADMIN</g:if>

你想使用一个圣杯过滤器 http://grails.org/Filters。使用过滤器,您可以指定要使用 before/after 和 afterView 方法拦截哪些控制器和方法(使用通配符)。

这使得将新变量填充到模型中变得容易,以便它在视图中可用。这是使用 acegi 插件authenticateService 的示例:

class SecurityFilters {

    def authenticateService

    def filters = {
        all(controller:'*', action:'*') {
            after = { model ->
                def principal = authenticateService.principal()
                if (principal != null && principal != 'anonymousUser') {
                    model?.loggedInUser = principal?.domainClass
                    log.debug("SecurityFilter: adding current user to model = $model")
                } else {
                    log.debug("SecurityFilter: anonymous user, model = $model")
                }
            }
        }
    }    
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

向grails中的所有视图添加变量 的相关文章

随机推荐