Is it possible to sort the tags object, in vanilla jinja, by "popularity", as in number of occurances of that tag? Here's the site displaying a tag-tree-kinda-thing, and here's the jinja loop I currently have.
I suspect I'll need to write a Pelican or jinja plugin to do this, like this poster did, but I thought I'd ask here, in case anyone has figured out a cool sorting technique.
Thanks for any help, and long live Pelican!
https://github.com/ingwinlu/sort_tags is available via the pelican-plugins repo.
A plugin is usually better since you won't be doing the sorting for each relevant render, but...
pelicanconf.py
from functools import partial
JINJA_FILTERS = {
'sort_by_article_count': partial(sorted,
key=lambda tag, articles: len(articles),
reversed=True)} # reversed for descending order
template
{% for tag, articles in tags|sort_by_article_count %}
Thanks @ingwinlu and @avaris! I'll give both of your suggestions a shot. I passed over that plugin because the description "pelican plugin to provide tags sorted by article length" misled me. I thought "why would I want to sort tags based on how long its articles are?" But now I suspect it means length as in len().
In case anyone else wants to use the filter approach, I found this to work:
from functools import partial
JINJA_FILTERS = {
'sort_by_article_count': partial(
sorted,
key=lambda tags: len(tags[1]),
reverse=True)} # reversed for descending order
The key function only takes on parameter (I suppose the filter is giveen tags, not tag,article in tags), and the sorted keyword arg is reverse. :)
@mwcz right, my bad. Sorry about that. The key function would receive (tag, articles) tuple. It should be
key=lambda (tag, articles): len(articles).
But that won't work in Python 3. Your version is better.
Most helpful comment
In case anyone else wants to use the filter approach, I found this to work:
The
keyfunction only takes on parameter (I suppose the filter is giveentags, nottag,article in tags), and the sorted keyword arg isreverse. :)