Accessing the model from a layout view in Grails
Asked Answered
F

1

5

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!

Flodden answered 2/2, 2009 at 13:58 Comment(0)
W
10

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>
Weisshorn answered 2/2, 2009 at 15:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.