Accessing the model from a layout view in Grails

£可爱£侵袭症+ 提交于 2019-11-30 21:11:16

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