views:

371

answers:

2

I want my main layout to conditionally put in some blocks of html that I want to be defined in a separate file.

I have more than one kind of navigation bar defined. I want to have a file for each navigation bar. Then I want to just set a variable in my controller or specific gsp file so that the layout chooses which navigator to use.

A: 

Yes, you just need to put conditions around g:render statements. You can either do

<% if (condition) { %>
 <g:render template="/common/topbar" />
<% } %>

or

<g:if test="yourcondition">
 <g:render template="/common/topbar" />

</g:if>
Jean Barmash
Hello Jean, I had problems using render inside of a layout. They worked great inside of a regular gsp. They came out unexecuted when they were part of a layout.
Andrew
+1  A: 

You can accomplish this in a few different ways. The first way that I'd suggest trying having something like this in your layout:

<g:if test="${nav == 'nav1'}">
     <g:render template="/nav/nav1" />
</g:if>
<g:elseif test="${nav == 'nav2'}">
     <g:render template="/nav/nav2" />
</g:elseif>
<g:else>
     <g:render template="/nav/default" />
</g:else>

In order for those templates to be rendered, you must have the following files:

  • grails-app/views/nav/_nav1.gsp
  • grails-app/views/nav/_nav2.gsp
  • grails-app/views/nav/_default.gsp

Notice that because the template is 'root-relative' that it resolved the template from the root of the grails-app/views directory. See the user guide section on Views and Templates for more.

Another method would be to dynamically render the navigation based on a parameter like this (in your Layout):

<g:render template="/nav/${nav ?: 'default'}" />

or if you want to go down the rabbit hole a little more, you could do something like this.

If you are still running into issues, then I'd imagine that there is something else that has been missed like passing some model parameters to the render tag.

Colin Harrington