Search code examples
tagsjekyllliquidcase-insensitive

Jekyll case-insensitive sorting


I'm trying to create a tags list in Jekyll. Some of the tags are "accessibility", "CSS", and "JavaScript". So my Jekyll code to create the list looks like this:

<ul>
  {% for item in (0..site.tags.size) %}{% unless forloop.last %}
    {% capture this_word %}{{ tag_words[item] }}{% endcapture %}
    <li>
      <a href="#{{ this_word | cgi_escape }}" class="tag">{{ this_word }}
        <span>({{ site.tags[this_word].size }})</span>
      </a>
    </li>
  {% endunless %}{% endfor %}
</ul>

However, the rending of the list isn't alphabetical. It's first case-sensitive, capital words first; so my example tags above are rendered in this order:

  • CSS
  • JavaScript
  • accessibility

Is there a way to make the sorted list case-insensitive?


Solution

  • There is a sort_natural filter in liquid, but it doesn't work with site.tags.

    The trick is to generate an array with all tags names

    {% comment %} Creates an empty array {% endcomment %}
    {% assign tags = "" | split:"" %}
    
    {% comment %}Creates an array of tags names{% endcomment %}
    {% for t in site.tags %}
      {% assign tags = tags | push: t[0] %}
    {% endfor %}
    

    Sort them naturally (case insensitive)

    {% assign sorted_tags = tags | sort_natural %}
    

    Based on this sort, print tags counts

    <ul>
    {% for t in sorted_tags %}
      <li>{{ t }} : {{ site.tags[t].size }}</li>
    {% endfor %}
    </ul>