2
votes

This question is really close to Shopify Sort cart.items array using Liquid script

I have unsorted sessions that I want to sort by date and by time (expected result: 1,2,3,4).

{  
    "date"=>"2014-06-24", 
    "time"=>"09:00", 
    "name"=>"Session 2",
}
{  
    "date"=>"2014-06-25", 
    "time"=>"08:45", 
    "name"=>"Session 3",
}
{  
    "date"=>"2014-06-24", 
    "time"=>"08:00", 
    "name"=>"Session 1",
}
{  
    "date"=>"2014-06-25", 
    "time"=>"09:45", 
    "name"=>"Session 4",
}

Here's the code:

{% assign time_sorted_instances = instances | sort: "time" %}
{% assign day_sorted_instances = time_sorted_instances | sort: "date" %}
{% for instance in instances %}
  {{ instance.date | date: "%A, %B %e, %Y" }} {{ instance.time }} {{ instance.session.name }}             <br>
{% endfor %}
{% for instance in time_sorted_instances %}
  {{ instance.date | date: "%A, %B %e, %Y" }} {{ instance.time }} {{ instance.session.name }}             <br>
{% endfor %}
{% for instance in day_sorted_instances %}
  {{ instance.date | date: "%A, %B %e, %Y" }} {{ instance.time }} {{ instance.session.name }}             <br>
{% endfor %}

I'm able to get either instances sorted by date (2,1,3,4), or by time (1,3,2,4), but not sorted one after another (1,2,3,4). The matching function in ruby would be:

sorted_instances = instances.sort{|i| [i.date,i.time]}

Here's the code for the sort option in Liquid: https://github.com/Shopify/liquid/blob/master/lib/liquid/standardfilters.rb#L112-L123

And obviously it's not possible. If someone has a work around, let me know!

1

1 Answers

2
votes

If using Javascript is an option, that could be an answer https://github.com/Shopify/liquid/issues/143#issuecomment-8718129

But I haven't found any Liquid only answer...