Quick'n'dirty Jekyll plugin for sorted cycle.
Copy sorted_for.rb
to _plugins/
directory of your Jekyll site.
Instead of for
in templates use sorted_for
. Add sort_by
parameter with property you want to sort by, or leave it out if the array contains primitives (i.e. strings or numbers). Also supports reversed
parameter as the original for
tag.
{% sorted_for node in site.pages reversed sort_by:weight %}
{{ node.title }}
{% endsorted_for %}
To use a custom sort property (eg. weight as in example above) add it to YAML Front Matter of your pages - see https://github.com/mojombo/jekyll/wiki/YAML-Front-Matter
String comparisons are case-insensitive by default, whether the collection contains strings or objects sorted by a string property. To enable case-sensitive string comparisons, apply the case_sensitive:true
parameter.
To iterate over the keys in a hash, use sorted_keys_for
.
{% sorted_keys_for tag in site.tags %}
<a href="/tags/{{ tag | downcase | replace:" ","-"}}.html">{{ tag }}</a><br />
Num posts: {{ site.tags[tag].size }}
{% endsorted_keys_for %}
To iterate over a nested array or hash, you will need to assign
the inner collection to a variable before iterating over it using sorted_for
or sorted_keys_for
. This example assumes that the total number of posts per year and per month are stored in two separate (parallel) hashes, where page.month_totals
is a hash-of-hashes:
<ul>
{% sorted_keys_for year in page.year_totals reversed %}
<li><a href="#{{ year }}">{{ year }}</a> - {{ page.year_totals[year] }} posts
<ul>
{% assign month_totals = page.month_totals[year] %}
{% sorted_keys_for month in month_totals reversed %}
<li><a href="#{{ year }}-{{month}}">{{ month | int_to_month_name }}</a>
- {{ month_totals[month] }} posts</li>
{% endsorted_keys_for %}
</ul>
</li>
{% endsorted_keys_for %}
</ul>
This example assumes that the total number of posts per year and per month are stored in a single hash-of-hashes:
<ul>
{% sorted_keys_for year in page.totals reversed %}
{% assign totals = page.totals[year] %}
<li><a href="#{{ year }}">{{ year }}</a> - {{ totals.year_total }} posts
<ul>
{% sorted_keys_for month in totals.month_totals reversed %}
<li><a href="#{{year}}-{{month}}">{{ month | int_to_month_name }}</a>
- {{ totals.month_totals[month] }} posts</li>
{% endsorted_keys_for %}
</ul>
</li>
{% endsorted_keys_for %}
</ul>
Hey are you interested in moving this into a repository? I've got a bug that I'd like to be able to send in a pull request for. I'm running into an error regarding subdirectories in gists (specifically
test/
) and I can't push changes to my own fork.