I need access to a specific model in my main.gsp layout. I have searched around and read that the best way to get this is to create an after filter and apply the model to the viewModel param and then access it in the gsp like so:
class MyFilters {
all(controller:'*', action:'*') {
after = {viewModel ->
viewModel.client = Client.get(session.clientId)
// println "Client is: ${client.toString()}"
}
}
}
And in my GSP, I should get “client” and be able to access it?
<g:if test="${client.isPartner()}">
Do something
</g:if>
<g:else>
Do something else
</g:else>
An example of what I’m trying to do is include GSP templates and include specific CSS stylesheets based on if the current client that is logged in belongs to a partner. The location of the special CSS and GSP templates depends on the partners name, so for example:
<g:if test="${client.isPartner()}">
<link rel="stylesheet" type="text/css" href="/partners/${client.getPartner().toString()}/css/style.css"/>
</g:if>
<g:else>
<link rel="stylesheet" type="text/css" href="/partners/default/css/style.css"/>
</g:else>
This would also be done with GSP templates… However, whenever I do this, I get an exception of:
ERROR grails.web.pages.GroovyPagesServlet - Original exception : Cannot invoke method isPartner() on null object
So, apparently “client” is null in the GSP. If I uncomment out the println in the after filter shown above, it is not null at this time and the name of the client is printed. Am I doing something wrong here? Is there a better way to get at a model inside of main.gsp?
This looks like a duplicate of a question I answered recently. I suggested solving this with a tag library:
How do I (or should I?) access the service layer from a SiteMesh template (views/layouts/main.gsp) in Grails?
You have access to the session in a tag lib, so a closure a bit like this ought to work:
Then you use the tag in your gsp something like this:
You can also pass attributes in, which are passed into the closure through the
attrsmap, if that’s helpful at all.Finally, if you want to conditionally render the body of the tag, then you can do that like this:
And you would call it like this: