I currently manage a blog using Eleventy as the static site generator, with Nunjucks as the templating language.
One of the features on my site is a page that displays all the tags assigned to my posts in alphabetical order along with the number of posts per tag.
However, I am now looking to rearrange the tags based on their frequency, starting with the most-used tags at the top.
The code snippet responsible for generating the current alphabetical list with post counts is:
<section id="tags-number-of-posts">
{% for tag2, posts2 in collections | dictsort %}
{% set tag2Url %}/tags/{{ tag2 | slug }}/{% endset %}
<a href="{{ tag2Url | url }}">{{ tag2 }} ({{ posts2 | length }})</a><br/>
{% endfor %}
</section>
Currently, the displayed result looks like this:
Blender (1)
boats (2)
Bomb Factory (1)
bonfires (4)
books (3)
but I would prefer it to be sorted by frequency like this:
bonfires (4)
books (3)
boats (2)
Blender (1)
Bomb Factory (1)
(The live version can be viewed at: .)
I have attempted changing the dictsort
to
sort(attribute="posts2.length")
, among other variations, but without success.
It seems that 'length' is not an attribute I can sort by directly. Is there a way to achieve this kind of sorting based on post counts? Should I consider incorporating lodash or employing a JavaScript function like map
?