在Grails的布局视图中访问模型 [英] Accessing the model from a layout view in Grails
问题描述
我在Grails中使用布局支持(sitemesh),它工作正常。我想调整我的布局以取决于用户是否登录。
我的grails-app / views / layouts / main。 gsp包含以下代码:
< g:if test =$ {user}>
用户名:$ {user.username}
< / g:if>
但是,看起来布局-GSP:无法访问模型,因此用户变量(我尝试时遇到无会话异常)。
预先感谢!
我的布局的推荐方式取决于用户是否登录或不是?
为此,我建议使用请求或会话范围。可能最干的方式是填充范围是一个过滤器。例如在文件grails-app / conf / SecurityFilters.groovy中(您需要创建它):
class SecurityFilters {
def filters = {
populateCurrentUser(controller:'*',action:'*'){
before = {
request.user = User.get (session.userId)
}
}
}
}
该示例假定您将当前用户的标识存储在会话属性userId中,并且您拥有一个Domain类User。在布局中使用它很简单:
< g:if test =$ {request.user} >
当前用户:$ {request.user.username}
< / g:if>
I'm using the layout support (sitemesh) in Grails which works fine. I'd like to adjust my layout to have it depend on whether or not a user is logged in or not.
My grails-app/views/layouts/main.gsp contains the following code:
<g:if test="${user}">
Username: ${user.username}
</g:if>
However, it appears as if the layout-GSP:s are unable to access the model and hence the user variable (I get a "No session" exception when trying). What would be the recommended way to make my layout depend on whether or not a user is logged in or not?
Thanks in advance!
I would suggest to use either the request or the session scope for that purpose. Probably the most DRY way is to populate the scope is a filter. For example in the file grails-app/conf/SecurityFilters.groovy (you'll need to create it):
class SecurityFilters {
def filters = {
populateCurrentUser(controller: '*', action: '*') {
before = {
request.user = User.get(session.userId)
}
}
}
}
The example assumes that you store the id of the current user in the session attribute "userId" and that you have a Domain class "User". Using it in the layout is as simple as this:
<g:if test="${request.user}">
Current User: ${request.user.username}
</g:if>
这篇关于在Grails的布局视图中访问模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!