Reputation: 97
This is very annoying. I tried to switch from a static to a dynamic nav in Jekyll, but now I am no longer able to assign a class to a link based on its url.
here how it was.
<nav class="site-nav">
<a href="{{ site.baseurl }}/about/" class="{% if page.url == '/about/' %}active{% endif %}">About</a>
<a href="{{ site.baseurl }}/archive/" class="{% if page.url == '/archive/' %}active{% endif %}">Archive</a>
<a href="{{ site.baseurl }}/resources/" class="{% if page.url == '/resources/' %}active{% endif %}">Resources</a>
<a href="{{ site.baseurl }}/books/" class="{% if page.url == '/books/' %}active{% endif %}">Books</a>
<a href="{{ site.baseurl }}/subscribe/" class="{% if page.url == '/subscribe/' %}active{% endif %}">Subscribe</a>
<a href="{{ site.baseurl }}/sample/" class="{% if page.url == '/sample/' %}active{% endif %}">sample</a>
</nav>
It worked. Then, I changed it to
<nav>
{% for menu in site.data.navigation[page.lang] %}
<a href="{{site.baseurl}}{{ menu[1].url }}" class="{% if page.url == '{{ menu[1].url | prepand: site.baseurl }}' %}active{% endif %}">{{ menu[1].title }}</a>
{% endfor %}
</nav>
Now it doesn't work. Any idea? The goal is to check the page.url against the nav menu url (menu[1].url) and if its identical apply the class "active". menu[1].url refers to content of _data/navigation, a yml file with menu list for two different nav based on page.lang.
the data file looks like this:
en:
about:
title: "about"
url: "/about/"
archive:
title: "archive"
url: "/archive/"
resources:
title: "resources"
url: "/resources/"
books:
title: "books"
url: "/books/"
sample:
title: "sample"
url: "/sample/"
it:
about:
title: "about"
url: "/about/"
archive:
title: "archive"
url: "/archive/"
resources:
title: "resources"
url: "/resources/"
books:
title: "books"
url: "/books/"
sample:
title: "sample"
url: "/sample/"
Upvotes: 1
Views: 706
Reputation: 52809
Here is the way I achieve this.
All posts and pages in an en
or fr
folder
--fr
|--_posts
|--about.html
|--...
--en
|--_posts
|--about.html
|--...
In _config.yml
add :
defaults:
# default lang is set to en
-
scope:
path: ""
values:
lang: "en"
# lang is set to fr in the fr folder
-
scope:
path: "fr"
values:
lang: "fr"
In order to sort my page in the navigation bar, I've added a weight
variable in pages front matter.
---
...
weight: 10
---
The code will generate navigation depending on current page lang.
<nav>
{% assign pages = site.pages | where: 'lang', page.lang | sort: 'weight' %}
{% for p in pages %}
{% if p.title %}
<a {% if p.url == page.url %} class="active"{% endif %} href="{{ site.baseurl }}{{ p.url }}">
{{ p.title }}
</a>
{% endif %}
{% endfor %}
</nav>
Upvotes: 1