Pelican: Is it possible to sort tags by count?

Created on 18 Mar 2015  路  5Comments  路  Source: getpelican/pelican

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!

Most helpful comment

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. :)

All 5 comments

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.

Was this page helpful?
0 / 5 - 0 ratings