3

Someone provided a solution, via the Craft Google community, but it was suggested that I also post it here for others to use.

<nav>
<ul>
<li><a href="{{ siteUrl }}" {% if craft.request.firstSegment == 'homepage' %} class="active" {% endif %}>Home</a></li>
<li><a href="{{ url('work') }}" {% if craft.request.firstSegment == 'work' %} class="active" {% endif %}>Work</a></li>
<li><a href="{{ url('about') }}" {% if craft.request.firstSegment == 'about' %} class="active" {% endif %}>About</a></li>
</ul>
</nav>

The above was adapted from the demo site install (I think) and although 'work' and 'about' work fine 'homepage' did not. I used 'homepage' as this is the 'handle' in the craft sections part of the cms so I thought that would be correct.

I initially found this How can I add a dynamic "active" CSS class to the navigation on any given page? but not being that dev focused found the many alternatives a bit confusing.

It was suggested that I add a 'section' to the homepage template and so I added {% set section = "home" %} after {% extends "_layout" %} in the homepage index.html.

I then amended my first <li> from above to be just

<li><a href="{{ siteUrl }}" {% if section == 'home' %} class="active" {% endif %}>Home</a></li>

which worked as required.

I hope that helps.

If anyone can explain why my original doesn't work, in layman's terms that would be much appreciated.

Thanks

Laurence

Matt Stein
  • 4,006
  • 3
  • 26
  • 57
Laurence
  • 33
  • 1
  • 4

1 Answers1

3

Unless the URL is domainname.com/homepage then your class will not get added.

Are you using template layouts? If you are you could have something like this in your _layout

{% block bodyClass %}{% if bodyClass is defined %}<body class="{{ bodyClass }}">
{% else %}<body>
{% endif %}

Then in your home template you would set it like so:

{% set bodyClass = 'CLASSNAME' %}

OR you could something like this in your nav:

<nav>
<ul>
<li><a href="{{ siteUrl }}" {% if craft.request.firstSegment == '' %}class="active"{% endif %}>Home</a></li>
<li><a href="{{ url('work') }}" {% if craft.request.firstSegment == 'work' %} class="active" {% endif %}>Work</a></li>
<li><a href="{{ url('about') }}" {% if craft.request.firstSegment == 'about' %} class="active" {% endif %}>About</a></li>
</ul>
</nav>

#

Hopefully that helps. If not you can always look at this post with other methods:

How can I add a dynamic "active" CSS class to the navigation on any given page?

Mark Busnelli Jr
  • 926
  • 7
  • 18
  • Thanks Mark, you somehow read my mind as I was interested in finding out how to add a class to the body as well. <li><a href="{{ siteUrl }}" {% if craft.request.firstSegment == '' %}class="active"{% endif %}>Home</a></li> worked to solve my original question me. – Laurence Oct 20 '14 at 21:20
  • Awesome :) I'm glad I could help, now just mark my response as an answer :) – Mark Busnelli Jr Oct 20 '14 at 21:22