Accessing the model from a layout view in Grails

后端 未结 1 349
南笙
南笙 2021-01-06 04:00

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

相关标签:
1条回答
  • 2021-01-06 04:41

    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>
    
    0 讨论(0)
提交回复
热议问题