<p>Assuming you use a structure called <code>pages</code> to create your navigation and the <code>entry</code> variable represents the currently viewed entry, you can output  your navigation and active state as follows:</p>

<pre class="lang-twig prettyprint-override"><code>&lt;ul&gt;
{% nav page in craft.entries.section('pages') %}
    &lt;li class="{{ page.id == entry.id ? 'active' }}"&gt;
        {{ page.link }}
        {% ifchildren %}
            &lt;ul&gt;
                {% children %}
            &lt;/ul&gt;
        {% endifchildren %}
    &lt;/li&gt;
{% endnav %}
&lt;/ul&gt;
</code></pre>

<p>See the <a href="http://buildwithcraft.com/docs/templating/tags#nav">nav tag</a> for more details.</p>

<p>If, instead of a structure, you are using a channel called <code>pages</code> for the navigation then the <code>nav</code> tag method above will still work but the following code is leaner and simpler to understand:</p>

<pre class="lang-twig prettyprint-override"><code>&lt;ul&gt;
{% for page in craft.entries.section('pages') %}
    &lt;li class="{{ page.id == entry.id ? 'active' }}"&gt;
        {{ page.link }}
    &lt;/li&gt;
{% endfor %}
&lt;/ul&gt;
</code></pre>

CC BY-SA 3.0
2014-06-28T15:03:29.730Z
Thanks Ben, I hadn't even looked into the nav tag, this only works for a structured section though, right? Still very useful, thank you.
Gareth
CC BY-SA 3.0
2014-06-30T09:01:10.473Z
it should work for a channel too, i updated my answer above with code for a channel though.
Ben Croker
CC BY-SA 3.0
2015-08-22T07:51:57.527Z
If using this with a dedicated menu section, this shouldn't work? Because nav items in this case are pages too and the ids of a nav item and a page corresponding to it are always different.
certainlyakey
CC BY-SA 3.0
2014-06-27T16:19:17.587Z
2014-06-30T20:25:43.153Z
2014-06-30T20:25:43.153Z
Ben Croker
<p><a href="http://buildwithcraft.com/docs/templating/craft.request"><strong>craft.request</strong></a> is useful for setting an "active" class based on URL segments. </p>

<p>If your URL was: <code>domain.com/sale/products/shirts</code></p>

<p>You could write conditionals like the following to target each segment:</p>

<pre><code>{% if craft.request.firstSegment == "sale" %}class="active"{% endif %}
{% if craft.request.segment(2) == "products" %}class="active"{% endif %}
{% if craft.request.lastSegment == "shirts" %}class="active"{% endif %}
</code></pre>

CC BY-SA 3.0
2014-06-28T18:18:18.900Z
Thanks Anna, I was thinking down this route, great minds :) thank you for your answer - have you seen Victor's suggestion using a macro with your code, looks  like a nice we to keep things DRY.
Gareth
CC BY-SA 3.0
2014-06-27T18:31:08.447Z
2014-06-27T18:31:08.447Z
Anna_MediaGirl
<p>Barrel Strength also have a URL segment based plugin called <a href="http://sprout.barrelstrengthdesign.com/craft-plugins/active">Sprout Active</a>, with <a href="http://sprout.barrelstrengthdesign.com/craft-plugins/active/docs/getting-started/introduction">docs/examples here</a>.</p>

CC BY-SA 3.0
2014-08-08T22:25:20.690Z
Sprout Active is great! I think the best solution for this.
Johannes Lamers
CC BY-SA 3.0
2014-06-27T14:46:04.213Z
2014-06-27T20:43:03.673Z
2014-06-27T20:43:03.673Z
Matt Stein
<p>Here's yet another way you can do it (in some circumstances) and it's nice and DRY:</p>

<p>Craft 2</p>

<pre><code>{% if craft.request.getPath() ==  entry.uri %}
</code></pre>

<p>Craft 3</p>

<pre><code>{% if craft.app.request.pathInfo ==  entry.uri %}
</code></pre>

CC BY-SA 3.0
2014-12-05T16:17:55.587Z
That doesn't seem tp work on the index page because entry.uri on the homepage is `__home__`
KSPR
CC BY-SA 4.0
2014-06-29T23:27:11.750Z
2018-11-19T19:53:11.730Z
2018-11-19T19:53:11.730Z
Simon Kuran
<p>In your template you can set a var in twig:</p>

<pre class="lang-twig prettyprint-override"><code>{% set active = 'blog' %}
</code></pre>

<p>And then in your navigation you can run an if statement to see what the var is</p>

<pre class="lang-twig prettyprint-override"><code>&lt;nav&gt;
    &lt;a {% if active = 'homepage' %}class="active"{% endif %}&gt; Home &lt;/a&gt;
    &lt;a {% if active = 'blog' %} class="active"{% endif %}&gt; Blog &lt;/a&gt;
&lt;/nav&gt;
</code></pre>

CC BY-SA 3.0
2014-06-28T15:07:03.907Z
Thank you Rob, this looks as if it works great until you re-use a template. Then I guess you would need to use a craft.request to check the segment variable?
Gareth
CC BY-SA 3.0
2014-06-30T14:36:51.050Z
Yeah you are probably right. For simple sites using Craft Personal you can get away with my above answer. However if you're doing something much larger, you might want to check out @Anna_MediaGirl's answer.
Rob Erskine
CC BY-SA 3.0
2014-06-27T13:45:00.397Z
2014-06-27T13:55:58.917Z
2014-06-27T13:55:58.917Z
Rob Erskine
<p>Another way to achieve this:</p>

<pre><code>    {% for entry in entries %}
      {% set active = craft.request.path ~ '/' matches "|^#{entry.uri}/|" %}
      &lt;a href="{{ entry.url }}" class="{{ active ? 'is-active' : '' }}"&gt;{{ entry.title }}&lt;/a&gt;
    {% endfor %}
</code></pre>

<p>This accounts for even when a navigation item might not be on the top level, but you want every URI that starts with that to trigger the active class.</p>

<p>Note: the pipes around the regex are just the encloser. They can be anything, but since we're dealing with URLs, it's easier not to use the standard <code>/</code>.</p>

CC BY-SA 3.0
2014-08-29T05:17:02.867Z
2014-08-29T05:42:38.263Z
2014-08-29T05:42:38.263Z
Tim Kelty
<p>Here's one more for this nice collection!</p>

<p>This is what I use for a structure "pages" where I needed some way to not only add a class <code>active</code> to the current entry, but also to all of the entry's ancestors. In an Example URL <code>http://example.com/beers/wheat-beers/</code> both links <code>beers</code> and <code>wheat-beers</code> should be given the <code>active</code>class.</p>

<p>The macro takes the structure entry's <a href="http://buildwithcraft.com/docs/templating/entrymodel#uri" rel="noreferrer"><code>uri</code></a> as one parameter. The other parameter is needed to specify the part of the current URL, the entry's URI gets compared to (→  <a href="http://buildwithcraft.com/docs/templating/craft.request#getSegment" rel="noreferrer"><code>craft.request.getSegment()</code></a>).</p>

<p>Give this parameter a value based on the entry's <a href="http://buildwithcraft.com/docs/templating/entrymodel#level" rel="noreferrer"><code>level</code></a> within its structure.</p>

<p>.</p>

<p><em>_macros.html:</em></p>

<pre><code>{% macro activeLinkClass(linkUri, requestSegmentNumber) %}

    {# Request the relevant path segment in the URL #}
    {% set nthRequestSegment = craft.request.segment(requestSegmentNumber) %}

    {# Split the link's URI into a list of path segments #}
    {% set linkSegments = linkUri|split('/') %}

    {# Get the path segment relevant for our comparison #}
    {% set nthLinkSegment = linkSegments[requestSegmentNumber - 1] %}

    {# Return `active` if the nthLinkSegment equals the nthRequestSegment #}
    {% if nthLinkSegment == nthRequestSegment %}active{% endif %}

{% endmacro %}
</code></pre>

<p>.</p>

<p><em>_navigation.html:</em></p>

<pre><code>{% import '_macros.html' as macros %}

{# Get entries from pages structure (exclude home page)  #}
{% set pages = craft.entries.section('pages').id('not 1') %}

{# Loop through entries and list the links #}
{% nav page in pages %}

    {# Add a class `active` if needed, using our macro #}
    &lt;a href="{{ page.url }}" class="nav-link{{ macros.activeLinkClass(page.uri, page.level) }}"&gt;
        {{ page.title }}
    &lt;/a&gt;

    {% ifchildren %}{% children %}{% endifchildren %}

{% endnav %}
</code></pre>

CC BY-SA 3.0
2014-08-29T09:07:32.453Z
2014-08-29T10:00:45.757Z
2014-08-29T10:00:45.757Z
carlcs
<p>I add a variable in my "_entry" template. </p>

<p>Here's a basic example:</p>

<pre class="lang-twig prettyprint-override"><code>{% extends "_layout" %}

{% set bodyClass = 'myPageType' %}

{% block content %}
&lt;!-- entry HTML here --&gt;
{% endblock %}
</code></pre>

<p>Then in my _layout template, it begins like this:</p>

<pre class="lang-twig prettyprint-override"><code>&lt;!doctype html&gt;
&lt;html class="{% if bodyClass is defined %}{{ bodyClass }}{% endif %}"&gt;
&lt;!-- the rest of the template follows --&gt;
</code></pre>

<p>Does something like that work for you?</p>

CC BY-SA 3.0
2014-06-28T18:20:12.670Z
Hey, John there are a few different options now, this page has become a great resource, thank you for your answer.
Gareth
CC BY-SA 3.0
2014-06-27T13:41:57.980Z
2014-06-27T13:56:27.253Z
2014-06-27T13:56:27.253Z
John Morton
<p>I think comparing the entry id's is the best way to go for the current page. But for determining if a certain page is a parent of the current page, I combined answers from @tim-kelty and @carlcs to come up with this:</p>

<pre><code>{% for entry in entries %}
  {% set isInSection = craft.request.firstSegment == entry.uri|split('/')[0] %}
  &lt;a href="{{ entry.url }}" class="{{ isInSection ? 'active' : '' }}"&gt;{{ entry.title }}&lt;/a&gt;
{% endfor %}
</code></pre>

<p>EDIT: I realized my above code does something slightly different than I originally thought: it will add the 'active' class to any items that are in the current' page's section... which includes siblings. If that's what you want, then it's great. But if you only want to indicate the actual top-level section parent page, then you should do this instead:</p>

<pre><code>{% for entry in entries %}
  {% set isTopParent = craft.request.firstSegment == entry.uri %}
  &lt;a href="{{ entry.url }}" class="{{ isTopParent ? 'active' : '' }}"&gt;{{ entry.title }}&lt;/a&gt;
{% endfor %}
</code></pre>

<p>Last but not least, if you want to hilite all pages that are in the parent "path" of the current page (which is what I most often need in my menus), you can do this:</p>

<pre><code>{# use different var name in the loop because we assume `entry` is already set to the currently-viewed page #}
{% for page in entries %}
  {% set isInPath = entry.uri matches '{^' ~ page.uri ~ '}' %}
  &lt;a href="{{ page.url }}" class="{{ isInPath ? 'active' : '' }}"&gt;{{ page.title }}&lt;/a&gt;
{% endfor %}
</code></pre>

<p>I've posted a full example that encompasses a lot of "denote the active page or its parents" logic here: <a href="http://craftcookbook.net/recipes/388" rel="nofollow">http://craftcookbook.net/recipes/388</a></p>

CC BY-SA 3.0
2015-08-04T05:47:55.070Z
2015-08-05T17:45:17.493Z
2015-08-05T17:45:17.493Z
Jordan Lev
<p>I know this post is old, but I'd like to share another technique I've been using for the past year. If you need a "hard-coded" navigation with no editing capabilities in the admin but still want dynamic information from the section ID number.</p>

<p>If you use multilingual sites, this is super practical because it will get the correct language page title, URL and check if it's currently active.</p>

<pre><code>&lt;li&gt;                    
    {% set homepage = craft.entries.id(13).one() %}
    &lt;a href="{{ homepage.getUrl }}" {% if craft.app.request.absoluteUrl == homepage.url %} class="active"{% endif %}&gt;{{ homepage.title }}&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;                    
    {% set about = craft.entries.id(23).one() %}
    &lt;a href="{{ about.getUrl }}" {% if craft.app.request.absoluteUrl == about.url %} class="active"{% endif %}&gt;{{ about.title }}&lt;/a&gt;
&lt;/li&gt;
</code></pre>

<p>As you can see in the example above I get 2 pages for my navigation, home and about pages.</p>

<p>Hopefully this helps out someone in the near future.</p>

CC BY-SA 4.0
2018-11-17T17:28:05.883Z
2018-11-17T17:28:05.883Z
mateostabio
<p><strong>Tip:</strong> To keep it short and reusable I would recommend that you wrap your preferred "check-method" in a Twig macro, I like <a href="https://craftcms.stackexchange.com/a/572/177">Anna's</a> version the most:</p>

<p><strong>_macros.html:</strong></p>

<pre class="lang-twig prettyprint-override"><code>{% macro is_active(segment) %}{% if craft.request.firstSegment == segment %}active{% endif %}{% endmacro %}
</code></pre>

<p><strong>layout.html:</strong></p>

<pre class="lang-twig prettyprint-override"><code>{% import "_macros.html" as macros %}

&lt;a href="{{ url('news') }}" class="{{ macros.is_active('news') }}"&gt;News&lt;/a&gt;
&lt;a href="{{ url('blog') }}" class="{{ macros.is_active('blog') }}"&gt;Blog&lt;/a&gt;
</code></pre>

CC BY-SA 3.0
2017-01-15T12:17:34.573Z
How would you test for pluralisation? So ('projects' || 'project') would both return an 'active' class?
Dan Christian
CC BY-SA 3.0
2014-06-27T18:44:11.267Z
2014-06-29T16:19:04.923Z
2017-04-13T12:51:00.200Z
Victor
<p>Just wondering how people approach setting a class of current in their navigation. Is there anything in Craft or Twig where you can set a conditional to check if a page is the current page. Or do you just need to set classes/ids on the body tag based on the segment?</p>

<p>Any ideas appreciated, Gareth</p>

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

(Asked by: username_0 on 2014-06-27)

Just wondering how people approach setting a class of current in their navigation. Is there anything in Craft or Twig where you can set a conditional to check if a page is the current page. Or do you just need to set classes/ids on the body tag based on the segment?

Any ideas appreciated, Gareth

**Tags:** conditional, navigation

---

## 11 answers

### Answer by username_14 on 2014-06-27. Score: 34 | Accepted answer

Tip: To keep it short and reusable I would recommend that you wrap your preferred "check-method" in a Twig macro, I like Anna's version the most:
_macros.html:
{% macro is_active(segment) %}{% if craft.request.firstSegment == segment %}active{% endif %}{% endmacro %}

layout.html:
{% import "_macros.html" as macros %}

News
Blog

> **Comments:**
> **username_15**: How would you test for pluralisation? So ('projects' || 'project') would both return an 'active' class?  

---

### Answer by username_1 on 2014-06-27. Score: 32

Assuming you use a structure called pages to create your navigation and the entry variable represents the currently viewed entry, you can output  your navigation and active state as follows:

{% nav page in craft.entries.section('pages') %}
    
        {{ page.link }}
        {% ifchildren %}
            
                {% children %}
            
        {% endifchildren %}
    
{% endnav %}


See the nav tag for more details.
If, instead of a structure, you are using a channel called pages for the navigation then the nav tag method above will still work but the following code is leaner and simpler to understand:

{% for page in craft.entries.section('pages') %}
    
        {{ page.link }}
    
{% endfor %}

> **Comments:**
> **username_0**: Thanks Ben, I hadn't even looked into the nav tag, this only works for a structured section though, right? Still very useful, thank you.  
> **username_1**: it should work for a channel too, i updated my answer above with code for a channel though.  
> **username_2**: If using this with a dedicated menu section, this shouldn't work? Because nav items in this case are pages too and the ids of a nav item and a page corresponding to it are always different.  

---

### Answer by username_3 on 2014-06-27. Score: 15

craft.request is useful for setting an "active" class based on URL segments. 
If your URL was: domain.com/sale/products/shirts
You could write conditionals like the following to target each segment:
{% if craft.request.firstSegment == "sale" %}class="active"{% endif %}
{% if craft.request.segment(2) == "products" %}class="active"{% endif %}
{% if craft.request.lastSegment == "shirts" %}class="active"{% endif %}

> **Comments:**
> **username_0**: Thanks Anna, I was thinking down this route, great minds :) thank you for your answer - have you seen Victor's suggestion using a macro with your code, looks  like a nice we to keep things DRY.  

---

### Answer by username_4 on 2014-06-27. Score: 13

Barrel Strength also have a URL segment based plugin called [Sprout Active](http://sprout.barrelstrengthdesign.com/craft-plugins/active), with [docs/examples here](http://sprout.barrelstrengthdesign.com/craft-plugins/active/docs/getting-started/introduction).

> **Comments:**
> **username_5**: Sprout Active is great! I think the best solution for this.  

---

### Answer by username_6 on 2014-06-29. Score: 12

Here's yet another way you can do it (in some circumstances) and it's nice and DRY:
Craft 2
{% if craft.request.getPath() ==  entry.uri %}

Craft 3
{% if craft.app.request.pathInfo ==  entry.uri %}

> **Comments:**
> **username_7**: That doesn't seem tp work on the index page because entry.uri on the homepage is `__home__`  

---

### Answer by username_8 on 2014-06-27. Score: 11

In your template you can set a var in twig:
{% set active = 'blog' %}

And then in your navigation you can run an if statement to see what the var is

     Home 
     Blog

> **Comments:**
> **username_0**: Thank you Rob, this looks as if it works great until you re-use a template. Then I guess you would need to use a craft.request to check the segment variable?  
> **username_8**: Yeah you are probably right. For simple sites using Craft Personal you can get away with my above answer. However if you're doing something much larger, you might want to check out @Anna_MediaGirl's answer.  

---

### Answer by username_9 on 2014-08-29. Score: 7

Another way to achieve this:
    {% for entry in entries %}
      {% set active = craft.request.path ~ '/' matches "|^#{entry.uri}/|" %}
      {{ entry.title }}
    {% endfor %}

This accounts for even when a navigation item might not be on the top level, but you want every URI that starts with that to trigger the active class.
Note: the pipes around the regex are just the encloser. They can be anything, but since we're dealing with URLs, it's easier not to use the standard /.


---

### Answer by username_10 on 2014-08-29. Score: 6

Here's one more for this nice collection!
This is what I use for a structure "pages" where I needed some way to not only add a class active to the current entry, but also to all of the entry's ancestors. In an Example URL http://example.com/beers/wheat-beers/ both links beers and wheat-beers should be given the activeclass.
The macro takes the structure entry's uri as one parameter. The other parameter is needed to specify the part of the current URL, the entry's URI gets compared to (→  craft.request.getSegment()).
Give this parameter a value based on the entry's level within its structure.
.
_macros.html:
{% macro activeLinkClass(linkUri, requestSegmentNumber) %}

    {# Request the relevant path segment in the URL #}
    {% set nthRequestSegment = craft.request.segment(requestSegmentNumber) %}

    {# Split the link's URI into a list of path segments #}
    {% set linkSegments = linkUri|split('/') %}

    {# Get the path segment relevant for our comparison #}
    {% set nthLinkSegment = linkSegments[requestSegmentNumber - 1] %}

    {# Return `active` if the nthLinkSegment equals the nthRequestSegment #}
    {% if nthLinkSegment == nthRequestSegment %}active{% endif %}

{% endmacro %}

.
_navigation.html:
{% import '_macros.html' as macros %}

{# Get entries from pages structure (exclude home page)  #}
{% set pages = craft.entries.section('pages').id('not 1') %}

{# Loop through entries and list the links #}
{% nav page in pages %}

    {# Add a class `active` if needed, using our macro #}
    
        {{ page.title }}
    

    {% ifchildren %}{% children %}{% endifchildren %}

{% endnav %}


---

### Answer by username_11 on 2014-06-27. Score: 6

I add a variable in my "_entry" template. 
Here's a basic example:
{% extends "_layout" %}

{% set bodyClass = 'myPageType' %}

{% block content %}

{% endblock %}

Then in my _layout template, it begins like this:




Does something like that work for you?

> **Comments:**
> **username_0**: Hey, John there are a few different options now, this page has become a great resource, thank you for your answer.  

---

### Answer by username_12 on 2015-08-04. Score: 4

I think comparing the entry id's is the best way to go for the current page. But for determining if a certain page is a parent of the current page, I combined answers from @tim-kelty and @carlcs to come up with this:
{% for entry in entries %}
  {% set isInSection = craft.request.firstSegment == entry.uri|split('/')[0] %}
  {{ entry.title }}
{% endfor %}

EDIT: I realized my above code does something slightly different than I originally thought: it will add the 'active' class to any items that are in the current' page's section... which includes siblings. If that's what you want, then it's great. But if you only want to indicate the actual top-level section parent page, then you should do this instead:
{% for entry in entries %}
  {% set isTopParent = craft.request.firstSegment == entry.uri %}
  {{ entry.title }}
{% endfor %}

Last but not least, if you want to hilite all pages that are in the parent "path" of the current page (which is what I most often need in my menus), you can do this:
{# use different var name in the loop because we assume `entry` is already set to the currently-viewed page #}
{% for page in entries %}
  {% set isInPath = entry.uri matches '{^' ~ page.uri ~ '}' %}
  {{ page.title }}
{% endfor %}

I've posted a full example that encompasses a lot of "denote the active page or its parents" logic here: http://craftcookbook.net/recipes/388


---

### Answer by username_13 on 2018-11-17. Score: 2

I know this post is old, but I'd like to share another technique I've been using for the past year. If you need a "hard-coded" navigation with no editing capabilities in the admin but still want dynamic information from the section ID number.
If you use multilingual sites, this is super practical because it will get the correct language page title, URL and check if it's currently active.
                    
    {% set homepage = craft.entries.id(13).one() %}
    {{ homepage.title }}

                    
    {% set about = craft.entries.id(23).one() %}
    {{ about.title }}


As you can see in the example above I get 2 pages for my navigation, home and about pages.
Hopefully this helps out someone in the near future.


---

