sort_collection 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. {% capture jbcache %}{% comment %}
  2. Sort the given array or map.
  3. Parameters:
  4. collection: the array or map to sort [REQUIRED]
  5. sort_by: the property to sort by [OPTIONAL]
  6. sort_descending: reverse the collection [OPTIONAL]
  7. Returns:
  8. sort_result: the sorted collection
  9. Examples:
  10. <h3>Pages</h3>
  11. <ol>
  12. {% include JB/sort_collection collection=site.pages sort_by="title" %}
  13. {% assign pages_list = sort_result %}
  14. {% include JB/pages_list %}
  15. </ol>
  16. <h3>Pages [Reversed]</h3>
  17. <ol>
  18. {% include JB/sort_collection collection=site.pages sort_by="title" sort_descending=true %}
  19. {% assign pages_list = sort_result %}
  20. {% include JB/pages_list %}
  21. </ol>
  22. <h3>Array</h3>
  23. <ol>
  24. {% assign test_array = "one,two,three,four" | split: "," %}
  25. {% include JB/sort_collection collection=test_array %}
  26. {% for test in sort_result %}
  27. <li>{{test}}</li>
  28. {% endfor %}
  29. </ol>
  30. <h3>Array [Reversed]</h3>
  31. <ol>
  32. {% assign test_array = "one,two,three,four" | split: "," %}
  33. {% include JB/sort_collection collection=test_array sort_descending=true %}
  34. {% for test in sort_result %}
  35. <li>{{test}}</li>
  36. {% endfor %}
  37. </ol>
  38. {% endcomment %}
  39. {% assign is_array = true %}
  40. {% assign sort_result = "," | split: "," %}
  41. {% assign collection = include.collection %}
  42. {% if include.sort_by %}
  43. {% assign sort_by = include.sort_by %}
  44. {% else %}
  45. {% assign sort_by = "title" %}
  46. {% endif %}
  47. {% if collection and collection.size > 0 %}
  48. {% for x in collection.first %}
  49. {% if x[1].size > 0 %}
  50. {% assign is_array = false %}
  51. {% endif %}
  52. {% break %}
  53. {% endfor %}
  54. {% if is_array == false %}
  55. {% assign sort_result = collection | sort: sort_by %}
  56. {% else %}
  57. {% assign sort_result = collection | sort %}
  58. {% endif %}
  59. {% if include.sort_descending %}
  60. {% assign reversed = "," | split: "," %}
  61. {% for index in (1..sort_result.size) %}
  62. {% assign i = sort_result.size | minus: index %}
  63. {% assign reversed = reversed | push: sort_result[i] %}
  64. {% endfor %}
  65. {% assign sort_result = reversed %}
  66. {% assign reversed = nil %}
  67. {% endif %}
  68. {% endif %}{% endcapture %}{% assign jbcache = nil %}