1
<ul class="nav">
    <li class="active"><a href="home.xhtml">Home</a></li>
    <li><a href="about.xhtml">About us</a></li>
    <li><a href="contact.xhtml">Contact us</a></li>                         
</ul>

Is there an easy way to template this using JSF so I dont have to include it on each page?

DD.
  • 21,498
  • 52
  • 157
  • 246
  • Check this first http://stackoverflow.com/q/6341427/1478467 (params should be what you are looking for to keep the active on the right menu) – Sherbrow Sep 18 '12 at 11:36

2 Answers2

12

You can use #{view.viewId} in EL to get the current view ID.

So, this should make it generic for all pages:

<ul class="nav">
    <li class="#{view.viewId == '/home.xhtml' ? 'active' : ''}"><a href="home.xhtml">Home</a></li>
    <li class="#{view.viewId == '/about.xhtml' ? 'active' : ''}"><a href="about.xhtml">About us</a></li>
    <li class="#{view.viewId == '/contact.xhtml' ? 'active' : ''}"><a href="contact.xhtml">Contact us</a></li>                         
</ul>

It'd be more DRY if you have a collection of pages somewhere in the EL scope:

<ul class="nav">
    <ui:repeat value="#{app.pages}" var="page">
        <li class="#{view.viewId == page.viewId ? 'active' : ''}"><h:link value="#{page.title}" outcome="#{page.viewId}" /></li>
    </ui:repeat>
</ul>

Note that the <h:link> will automatically prepend the context path in the URL, so having / in the view ID doesn't matter.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • if all my files are in a directory e.g. /secure/home.xhtml, is there a way of doing "#{view.viewId == '/secure/home.xhtml' ? 'active' : ''}" without having to reference secure? – DD. Sep 26 '12 at 17:42
  • `
  • ... `.
  • – BalusC Sep 26 '12 at 20:21