Tuesday, December 24, 2013

Ya Sure, You Betcha - It's a Sortin' Huginn Pluginn

Or plugin. Anyway - Huginn plugin architecture is simple. You only need a module that exposes 1 function that accepts 1 parameter - the site object. Everything else is a property of the site object.

Plugins are called after all the site date, posts, and drafts have been loaded, and before any output has been processed. This makes the sort plugin almost trivial.

First, update config.yml with the sort parameters:

  src: posts
  by: date
  direction: asc
  dest: posts_asc
Next, copy the code to the _plugins folder:

module.exports = (site) ->

  by = site.sort.by ? 'date'

  # Get the list of items to sort
  site[site.sort.dest] = (item for item in site[site.sort.src])

  # sort in descending or ascending order
  site[site.sort.dest].sort switch site.sort.direction ? 'asc'
    when 'desc'
      (a, b) ->
        if a[by] < b[by] then 1 else if a[by] > b[by] then -1 else 0
      (a, b) ->
        if a[by] > b[by] then 1 else if a[by] < b[by] then -1 else 0
Finally, we're going to add this fragment to our template:

{% for post in site.posts_asc limit: 5 %}
  • {{ post.title }}
  • {% endfor %} ...
    I use this to sort the game list on Katra

    (updated: to use google prettify rather than embedded gists. It makes it easier to focus on the code)

    No comments:

    Post a Comment