A quick and dirty way to use variable collection names

There are certainly better solutions than the one here, but this is one easy with only a single caveat.

Lets say you use 11ty and are using a single nunjucks template for multiple related content groups and don't want to jump through lots of hoops to filter them all for, oh lets say, back and forward buttons on each page within a given group. (Sort of like the works pages on this site.)

The solutions to be found on Stack Overflow mostly go on about creating new variables that can then be grabbed by a script and used as if it were a collection, which, since they don't necessarily auto-iterate, then require additional code to work through.

I thought about that and realized, well, we already had a variable, and it is directly used by collections. It is called tags. And the only catch to using it as a variable in collections instead of using its properties directly is you need to be consistent about which tag in the tag array is the one you are looking for.

I recommend the first one, aka, tags[0].

Then you can modify the standard back and forward buttons as follows:

{% set p = collections[tags[0]] | getPreviousCollectionItem(page) %}
{% set n = collections[tags[0]] | getNextCollectionItem(page) %}

Rest works exactly the same.

<nav aria-label="see more stuff">
{% if p %}<a href="{{ p.url }}">prev</a>
{% else %}<span class="nolink">prev</span>
{% endif %}
{% if n %}<a href="{{ n.url }}">next</a>
{% else %}<span class="nolink">next</span>
{% endif %}