Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a sorted tags_list in jekyll

Tags:

jekyll

I'm using jekyll-bootstrap to maintain a blog on GitHub.

I'd like to have a sorted tags_list. The tag with the most posts comes first. Then I can have a display that shows the first tags with bigger font-size and last tags with smaller font-size. And I also want a splice function.

If in python/Jinja2, I'd like some code like this:

{% for tag in sorted_tags[:10] %}
  <li style="font-size:{{ tag.count }}px;">{{ tag.name }}</li>
{% endfor %}

What's the equivalent implementation in ruby/jekyll?

like image 882
hbrls Avatar asked Oct 23 '12 07:10

hbrls


1 Answers

This is how I'm sorting by the number of posts in a tag (descending), without any plugins (i.e. GitHub Pages compatible).

It also works when your tag names contain spaces; only , and : are forbidden characters (but you can easily change those).

{% capture counts_with_tags_string %}{% for tag in site.tags %}{{ tag[1] | size | prepend:"000000" | slice:-6,6 }}:{{ tag[0] }}{% unless forloop.last %},{% endunless %}{% endfor %}{% endcapture %}
{% assign counts_with_tags = counts_with_tags_string | split:"," | sort | reverse %}

<ol>
  {% for count_with_tag in counts_with_tags %}
    {% assign tag = count_with_tag | split:":" | last %}
    {% assign count = site.tags[tag] | size %}
    <li><a href="/blog/tags/{{ tag | slugify }}">{{ tag }} ({{ count }})</a></li>
  {% endfor %}
</ol>

It's super gross. What it does:

  • counts_with_tags_string is set to a string like 000005:first_tag,000010:second_tag,000002:third_tag. The zero-padded numbers are generated using the filter chain | prepend:"000000" | slice:-6,6.
  • This is split on commas and sorted lexicographically, which works because of the zero padding. The result is assigned to counts_with_tags.
  • Finally, we iterate over the elements and split each on : to find the original tag name. We could find the count in the same way, but because it's zero padded, it's easier to look it up using site.tags[tag] | size instead.
like image 127
Thomas Avatar answered Nov 02 '22 00:11

Thomas