4
votes

I made a liquid template for navigation menu and tried to add active css rule to current active menu item.

Here are my liquid tag to render the menu item:

<ul class="list-inline float-right">
    {% assign menu_pages = site.pages | sort: 'index' %}
    {% for p in menu_pages limit 3 %}
        {% if page.menu_title and page.url == p.url %}
        <li class="active"><a href="{{ p.url | prepend: site.baseurl }}">{{ p.menu_title }}</a></li>
        {% else %}
        <li><a href="{{ p.url | prepend: site.baseurl }}">{{ p.menu_title }}</a></li>
        {% endif %}
    {% endfor %}
</ul>

index is a yaml front matter variable to sort menu items.
menu_title is a yaml front matter variable to add custom menu title shown on the menu bar.

I add those two front matter variables above directly to my .html file in root which are going to be rendered as pages.

But when I checked this on browser, I got another blank menu items that link me to my main.css and framework.css file.

Here is the rendered html:

<ul class="list-inline float-right">
    <li><a href="/css/main.css"></a></li>
    <li><a href="/css/framework.css"></a></li>
    <li class="active"><a href="/">Home</a></li>
    <li><a href="/works/">Works</a></li>
    <li><a href="/blog/">Blog</a></li>
</ul>

This happened right after I include my main.sass and framework.sass file to Jekyll assets which located in css folder while the partial sass file in _sass folder. I assume the front matter makes those two sass file being rendered as pages and this is because of yaml front matter I added to my two sass file. I tried to delete the double --- line on top of them then I refresh the localhost and the blank menu items gone.

I have three menu items to be rendered:

  • Home
  • Works
  • Blog

but the result is five!

So is it true that this because the yaml front matter? How can I fix this while using Jekyll sass assets pipeline?

2

2 Answers

2
votes

In this case you'd be better to use site.html_pages instead:

{% assign menu_pages = site.html_pages | sort: 'index' %}

From https://jekyllrb.com/docs/variables/#site-variables, site.html_pages is:

A subset of site.pages listing those which end in .html.

1
votes

Your if clause is filtering on menu_title but the else clause is not filtering. You can change your condition to :

{% if page.menu_title %}
  <li{% if page.url == p.url %} class="active">{% endif %}
    <a href="{{ p.url | prepend: site.baseurl }}">{{ p.menu_title }}</a>
  </li>
{% endif %}