Technically Feasible

Eleventy - Sorting

Likeness of Michael Oldroyd
Michael Oldroyd

I'm learning Eleventy. Coming from writing (mostly) strictly typed code, JS is really frustrating. It's possibly because I'm using VS Code instead of Intellij, but I don't know how method or type hinting could work. I'll try it out at some point.

I figured out a basic method to sort Eleventy collections;

// Sort with `Array.sort`
eleventyConfig.addCollection("sortedNav", function(collection) {
    return collection.getFilteredByTag("nav").sort(function(a, b) {
        return a.data.priority - b.data.priority;
    });
});

I'm using this to sort the nav collection, which is the main navigation at the top of the page. You simply add a frontmatter item named priority;

title: Some Page
tags:
- nav
priority: 1

Finally, you need to switch whatever code is loading the nav collection to use the new sortedNav collection instead;

<ul class="nav page-header__nav">
    {%- for nav in collections.sortedNav -%}
    <li class="nav-item{% if nav.url == page.url %} nav-item-active{% endif %}"><a href="{{ nav.url | url }}">{{ nav.data.navtitle }}</a></li>
    {%- endfor -%}
</ul>
Image of me

Michael Oldroyd

Michael is a Software Engineer working in the North West of England.