Accessing the model from a layout view in Grails

痞子三分冷 提交于 2019-11-30 05:43:20

问题


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!


回答1:


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>


来源:https://stackoverflow.com/questions/503279/accessing-the-model-from-a-layout-view-in-grails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!