<p>You can get the current Category Model via the pre-populated <code>category</code> variable on all of your category pages. (→ see <a href="http://buildwithcraft.com/docs/routing" rel="nofollow">Routing type no. 4</a>)</p>

<p>As you probably know, entry pages come with <code>entry</code> pre-populated. To get all the Category Models that are related to an entry page with a Categories Field make a <code>craft.categories</code> call using <code>relatedTo(entry)</code> as a parameter.</p>

<p>Save the Category Model / -Models to a var outside your <code>nav</code> loop, so you don't have to make those requests multiple times. And make sure to save the one Category Model on category pages as an array <code>[myCategoryModel]</code>, so you always end up with your variable being of the same type.</p>

<p>Within you <code>nav</code> loop you can now check, if the Category Model of your current loop iteration is within your saved array using the <a href="http://twig.sensiolabs.org/doc/templates.html#containment-operator" rel="nofollow"><code>in</code></a> containment operator.</p>

<pre><code>{# Is this an entry page with a category field? #}
{% if entry is defined %}
    {% set currentCategoryIds = craft.categories.relatedTo(entry).ids() %}
{# Is this a category page? #}
{% elseif category is defined %}
    {% set currentCategoryIds = [category.id] %}
{# None of both? Set an empty array. #}
{% else %}
    {% set currentCategoryIds = [] %}
{% endif %}

{% nav cat in craft.categories.group('artCats') %}

    {% set class = cat.id in currentCategoryIds ? 'current' : '' %}
    {% set entryCount = craft.entries.relatedTo(cat).total() %}

    &lt;li&gt;&lt;a href="{{ cat.url }}" class="{{ class }}"&gt;{{ cat.title }} ({{ entryCount }})&lt;/a&gt;&lt;/li&gt;

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

CC BY-SA 3.0
2015-02-16T16:43:21.953Z
If i do that, i get the following error: Variable "entry" does not exist. It highlights that very first line as where the error happens.
The site homepage doesn't throw that error, it only happens when i am in a category page like sitename.com/categoryname
Dan Owen
CC BY-SA 3.0
2015-02-16T16:54:05.127Z
@DanOwen Ahh sorry, I made the code to only work for entry pages (single, channel or structure entries with a categories field). Will try to change this...
carlcs
CC BY-SA 3.0
2015-02-16T17:03:10.440Z
@DanOwen I'm actually not sure if a category page automatically comes with a Category Model pre-assigned to the var `category`. If it does, the updated code could work ;)
carlcs
CC BY-SA 3.0
2015-02-16T17:20:55.453Z
@carlcs It does. I was wondering the same and just checked.
Douglas McDonald
CC BY-SA 3.0
2015-02-16T17:54:42.073Z
@carlcs Sounds good! BUT! It still throws that error for me on category list pages (it flag up the very first {% if entry %} as the error). That is, if a user clicks a category name, it lists all of the entries in that category (so im not in a page with a category field)
Dan Owen
CC BY-SA 3.0
2015-02-16T18:12:50.067Z
@DanOwen still no luck?
carlcs
CC BY-SA 3.0
2015-02-16T21:33:00.330Z
@carlcs Sorry for the slow reply! Well i don't get an error now. But now instead all of my links have class="" in them.
Dan Owen
CC BY-SA 3.0
2015-02-17T12:38:56.547Z
@DanOwen ok, it's probably the CategoryModels that make trouble with the `in` operator. Changed the code to use their IDs now, hope this helps.
carlcs
CC BY-SA 3.0
2015-02-17T13:57:03.213Z
@carlcs Same result again! I had to change what you have as cat.id to category.id else it threw an error. Thank you for your persistence on this! It's quite a head scratcher.
Dan Owen
CC BY-SA 3.0
2015-02-17T15:12:58.563Z
@DanOwen could you please try the whole code block as posted (remove all other nav)? I'm pretty sure this should work now!
carlcs
CC BY-SA 3.0
2015-02-17T15:13:29.320Z
Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/21190/discussion-between-carlcs-and-dan-owen).
carlcs
CC BY-SA 3.0
2015-02-17T16:09:37.273Z
@carlcs Yes! That did it :^) Thank you so much for taking the time to help me with this!
Dan Owen
CC BY-SA 3.0
2015-02-16T16:16:56.057Z
2015-02-17T12:37:18.597Z
2015-02-17T12:37:18.597Z
carlcs
<p>I've browsed the questions and answers here and i can't find anything that works for what i'm trying to do!</p>

<p>I am using this as the main menu of my site (so it is in _layout.html)</p>

<pre><code>{% nav category in craft.categories.group('artCats') %}
{% set entryCount = craft.entries.relatedTo(category).total()
  &lt;li&gt;&lt;a href="{{ category.url }}"&gt;&lt;span&gt;{{ category.title }}&lt;/span&gt;{% if category.level == 2 %}&lt;span class="postnum"&gt;({{ entryCount }})&lt;/span&gt;{% endif %}&lt;/a&gt;
  {% ifchildren %}
    &lt;ul&gt;
      {% children %}
    &lt;/ul&gt;
  {% endifchildren %}
  &lt;/li&gt;
{% endnav %}
</code></pre>

<p>It's a drop down menu that shows how many posts are in each sub category. All works nicely!</p>

<p>However, no matter what i try, i can't seem to dynamically assign a class to the current page. I think i'm misunderstanding in general how this is done in Craft.</p>

<p>I see a lot of solutions that are basically saying "if url segment is "fishcake" then add my class" but to me, that's not dynamic at all! Dynamic would be if i add a new sub-category, the menu will add my desired class to that menu item if i visit, without me having to add a new if statement in the Twig code.</p>

<p>Am i able to do something like "if the category.url of this link matches the current url, do this" ?</p>

<categories><navigation>
How can i apply "current" class for category nav?
# How can i apply "current" class for category nav?

(Asked by: username_0 on 2015-02-16)

I've browsed the questions and answers here and i can't find anything that works for what i'm trying to do!
I am using this as the main menu of my site (so it is in _layout.html)
{% nav category in craft.categories.group('artCats') %}
{% set entryCount = craft.entries.relatedTo(category).total()
  {{ category.title }}{% if category.level == 2 %}({{ entryCount }}){% endif %}
  {% ifchildren %}
    
      {% children %}
    
  {% endifchildren %}
  
{% endnav %}

It's a drop down menu that shows how many posts are in each sub category. All works nicely!
However, no matter what i try, i can't seem to dynamically assign a class to the current page. I think i'm misunderstanding in general how this is done in Craft.
I see a lot of solutions that are basically saying "if url segment is "fishcake" then add my class" but to me, that's not dynamic at all! Dynamic would be if i add a new sub-category, the menu will add my desired class to that menu item if i visit, without me having to add a new if statement in the Twig code.
Am i able to do something like "if the category.url of this link matches the current url, do this" ?

**Tags:** categories, navigation


---

## 1 answers

### Answer by username_1 on 2015-02-16. Score: 5 | Accepted answer

You can get the current Category Model via the pre-populated category variable on all of your category pages. (→ see Routing type no. 4)
As you probably know, entry pages come with entry pre-populated. To get all the Category Models that are related to an entry page with a Categories Field make a craft.categories call using relatedTo(entry) as a parameter.
Save the Category Model / -Models to a var outside your nav loop, so you don't have to make those requests multiple times. And make sure to save the one Category Model on category pages as an array [myCategoryModel], so you always end up with your variable being of the same type.
Within you nav loop you can now check, if the Category Model of your current loop iteration is within your saved array using the in containment operator.
{# Is this an entry page with a category field? #}
{% if entry is defined %}
    {% set currentCategoryIds = craft.categories.relatedTo(entry).ids() %}
{# Is this a category page? #}
{% elseif category is defined %}
    {% set currentCategoryIds = [category.id] %}
{# None of both? Set an empty array. #}
{% else %}
    {% set currentCategoryIds = [] %}
{% endif %}

{% nav cat in craft.categories.group('artCats') %}

    {% set class = cat.id in currentCategoryIds ? 'current' : '' %}
    {% set entryCount = craft.entries.relatedTo(cat).total() %}

    {{ cat.title }} ({{ entryCount }})

{% endnav %}

> **Comments:**
> **username_0**: If i do that, i get the following error: Variable "entry" does not exist. It highlights that very first line as where the error happens. The site homepage doesn't throw that error, it only happens when i am in a category page like sitename.com/categoryname  
> **username_1**: @DanOwen Ahh sorry, I made the code to only work for entry pages (single, channel or structure entries with a categories field). Will try to change this...  
> **username_1**: @DanOwen I'm actually not sure if a category page automatically comes with a Category Model pre-assigned to the var `category`. If it does, the updated code could work ;)  
> **username_2**: @username_1 It does. I was wondering the same and just checked.  
> **username_0**: @username_1 Sounds good! BUT! It still throws that error for me on category list pages (it flag up the very first {% if entry %} as the error). That is, if a user clicks a category name, it lists all of the entries in that category (so im not in a page with a category field)  
> **username_1**: @DanOwen still no luck?  
> **username_0**: @username_1 Sorry for the slow reply! Well i don't get an error now. But now instead all of my links have class="" in them.  
> **username_1**: @DanOwen ok, it's probably the CategoryModels that make trouble with the `in` operator. Changed the code to use their IDs now, hope this helps.  
> **username_0**: @username_1 Same result again! I had to change what you have as cat.id to category.id else it threw an error. Thank you for your persistence on this! It's quite a head scratcher.  
> **username_1**: @DanOwen could you please try the whole code block as posted (remove all other nav)? I'm pretty sure this should work now!  
> **username_1**: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/21190/discussion-between-username_1-and-dan-owen).  
> **username_0**: @username_1 Yes! That did it :^) Thank you so much for taking the time to help me with this!  

---

