Skip to content

Instantly share code, notes, and snippets.

@morgyface
Created October 18, 2023 16:47
Show Gist options
  • Save morgyface/7a6ba134fed3653471fc7a5234d3005b to your computer and use it in GitHub Desktop.
Save morgyface/7a6ba134fed3653471fc7a5234d3005b to your computer and use it in GitHub Desktop.
11ty | Nunjucks | Featured items using next and previous
@morgyface
Copy link
Author

Featured pages in 11ty

This took me a while to suss out, so as with anything I write that might be useful to others or my future self I'm publicly posting it here.

The problem

I was building a site for my own carpentry business using 11ty and had a collection of services. When on a services page I wanted to display two other featured services underneath the main content.

Next and previous filter

In WordPress I'd probably create a custom field allowing selection with a fallback, but with 11ty I wasn't sure of the best way to go about this until I discovered Get Next or Previous Collection Item Universal Filters which allowed me to grab page objects for the next and previous items in the collection.

First and last

I was nearly there but the issue was, when the page was the first item in a collection it didn't have a previous item, similarly the last item didn't have a next item. I solved this using the Nunjucks built in filters first and last which allowed me to grab the first and last items in a collections array.

The push

So all that was left to do now was to create an array and use push to insert the two gathered objects into an array which could then be looped through.

Limitations

This thing is only going to work if there are 3 or more items in a collection. This also only works if you want 2 featured items. Other than that it does the trick nicely and I'm pretty pleased with myself. Might treat myself to a biscuit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment