grailsgsp

Grails set active tab in layout


Is there a good pattern to highlight the active navigation tab while at the same time keeping the shared navigation structure in the main.gsp layout? My main.gsp sets up the nav bar like this:

<ul class="nav nav-pills">
  <li class="nav-item">
      <g:link controller="controller1" class="nav-link">Controller 1</g:link>
  </li>
  <li class="nav-item">
      <g:link controller="controller2" class="nav-link">Controller 2</g:link>
  </li>
</ul>

when the page renders I want to be able to add the active class to the appropriate nav-link based on the identity of the controller.

I'm thinking I could maybe do something with pageParameters, but it feels a little kludgey. Is there a good pattern for setting the active UI element for structures defined in the layout? Is it possible to write something like this in the layout:

<g:link controller="controller1" class="nav-link ${ controller == 'controller1' ? 'active' : '' }">Controller 1</g:link>

Solution

  • This post describes how to achieve what I wanted without page properties: Twitter Bootstrap active navbar in grails

    The essential part of making this work was using the property controllerName that Grails automatically makes available within the scope where the layout is rendered. For example:

    <li class="${controllerName.equals('controller1') ? "active" : "" }">controller1</li>