从 Grails 中的布局视图访问模型 [英] Accessing the model from a layout view in Grails

查看:19
本文介绍了从 Grails 中的布局视图访问模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Grails 中使用了布局支持 (sitemesh),效果很好.我想根据用户是否登录来调整我的布局.

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.

我的 grails-app/views/layouts/main.gsp 包含以下代码:

My grails-app/views/layouts/main.gsp contains the following code:

<g:if test="${user}">
  Username: ${user.username}
</g:if>

但是,似乎 layout-GSP:s 无法访问模型,因此无法访问用户变量(尝试时出现无会话"异常).使我的布局取决于用户是否登录的推荐方法是什么?

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?

提前致谢!

推荐答案

我建议为此目的使用请求或会话范围.可能最干燥的方法是填充范围是过滤器.例如在文件 grails-app/conf/SecurityFilters.groovy 中(您需要创建它):

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)
            }
        }
    }
}    

该示例假设您将当前用户的 id 存储在会话属性userId"中,并且您有一个域类User".在布局中使用它就像这样简单:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆