How can i apply "current" class for category nav? 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()
  &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 %}


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" ?
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() %}

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

{% endnav %}