ARCJSCHMIDT.de
Thoughts from a developer//entrepreneur.
Founder of AETROS.com

open-source

php|Propel1 php|Propel2 php|CDS php|PHP-PM php|php-pm-httpkernel web|Jarves.io web|css-element-queries js|jQuery-selectBox php|PropelBundle php|Propel Sandbox js|angular2-localStorage js|angular-es6-annotations php|php-rest-service php|topsort.php xxx|BetterQuitJobBundle js|angular-typescript-decorators c++|node-core-audio php|optimistic-locking-behavior php|change-logger-behavior

github.com/marcj twitter.com/MarcJSchmidt plus.google.com/+MarcJSchmidt RSS xing.com/profile/MarcJ_Schmidt

Jekyll, dynamic navigation with active css class.

25 October 2013, by Marc

While I was thinking about a system for my new blog I thought I should use just Jekyll. Jekyll is pretty cool, but doesn’t have really much helper utils to get common tasks done well and fast. So since I don’t want to for example ‘hardcode’ my navigation list in HTML directly (although I could :-P) I worked out an alternative, configurable way.

It needed a bit of research to get this smooth working but I finally got it.

Define navigation list in your _config.yml:

navigation:
 - title: Home
   url: /index.html
 - title: Projects
   url: /projects.html
 - title: About
   url: /about.html
 - title: Contact
   url: /contact.html

Use following HTML code in your layout file:

<nav>
    <ul>
    {% for link in site.navigation %}
        {% assign current = nil %}
        {% if page.url contains link.url %}
            {% assign current = 'current' %}
        {% endif %}
        <li class="element {% if forloop.first %}first{% endif %} {{ current }} {% if forloop.last %}last{% endif %}">
            <a href="{{ link.url }}">{{ link.title }}</a>
        </li>
    {% endfor %}
    </ul>
</nav>

You can style then your navigation through nav li selector and active elements with nav li.current a.

Example:

nav a {
    text-decoration: none;
}

nav li {
    line-height: 25px;
    font-size: 14px;
    text-transform: uppercase;
}

nav li.current a {
    color: #111;
}

nav ul {
    list-style-type: none;
    padding: 0;
}

As extra sugar, you got li.first and li.last as well to style those navigation items.