Adding "active" class to menu not working for files inside _data folder

I am trying to add an “active” class to the categories on my main menu when the category is opened and also for the category when a single post in that category is opened. All posts in the _posts folder are in folders bearing the category names. I can get the active class to work when I hard code all the menu items like this

<ul class="nav-menu">
      <li {% if page.url contains '/category/name/' or page.path contains "_posts/category-name" %}class="active" aria-current="page"{% endif %}><a href="/category/name/">Category Name</a></li>
    </ul>

But it does not work if I create the navigation inside a nav.yaml file like this

- title: Category Name
  url: /category/name/
  path: _posts/category-name

and then add this to header.html

<ul class="nav-menu">
      {% for nav in site.data.nav %}
      <li {% if page.url contains '{{nav.url}}' or page.path contains "{{nav.path}}" %}class="active" aria-current="page"{% endif %}><a href="{{nav.url}}">{{nav.title}}</a></li>
     {% endfor %}
    </ul>

I am trying not to hard code the menu items, so my question is, how do I get the items in the _data file to work as expected?

I don’t think you need the double curlies when inside the {% %} block - I saw someone post something about that here recently. I’d try it without. Next question would be the quotes around the variable, not too sure about that, might not need those either since it is a variable of sorts and not a string?

  • Do not wrap your variables in quotes. Quoted contents are parsed as literal strings.
  • Do not use {{ and }} to enclose variables within Liquid core tags. Such syntax is only valid in Jekyll tags such as {% link ... %} or {% include ... %} or their derivatives.

The desired template is therefore:

<ul class="nav-menu">
  {% for nav in site.data.nav %}
    <li {% if page.url contains nav.url or page.path contains nav.path %}class="active" aria-current="page"{% endif %}>
      <a href="{{ nav.url }}">{{ nav.title }}</a>
    </li>
  {% endfor %}
</ul>

Note: Using the template above is fine as long as you’re crafting data carefully.
For example, if your data file had contained an entry such as url: /category/, then the if condition will be true for all category pages.

Thanks a lot. It worked.