将一个变量添加到grails中的所有视图 [英] Adding a variable to all views in grails
问题描述
我试图为所有视图中的当前用户(POJO)设置一个变量,以便我可以获取用户名等内容并检查其在每个视图(包括默认布局)上的角色。我如何在grails中设置一些东西(例如currentUser),以便在每个Grails视图中都可以这样访问:
I am trying to set a variable for the current user (a POJO) in all views so I can get things like the user name and check their role on every view (including the default layout). How can I setup something (e.g. currentUser) in grails so that it is accessible in every grails view like so:
<div>${currentUser.name}</div>
或者像这样:
or like this:
<g:if test="${currentUser.admin}">ADMIN</g:if>
推荐答案
您想使用 grails过滤器。使用过滤器,您可以指定您想要在前/后和afterView方法中使用哪些控制器和方法(使用通配符)。
You want to use a grails filter. Using a filter, you can specify which controllers and methods (using wild cards) you want to intercept using before/after and afterView methods.
这可以很容易地填充将新变量放入模型中,以便在视图中可用。下面是一个使用acegi插件authenticateService的例子:
This makes it easy to stuff a new variable into the model so it's available in a view. Here's an example that uses the acegi plugin 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")
}
}
}
}
}
这篇关于将一个变量添加到grails中的所有视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!