Skip to content
This repository was archived by the owner on Nov 30, 2024. It is now read-only.

Commit 559baaf

Browse files
committed
Merge pull request #250 from groundh0g/issue-42
Stand-alone helper. Low risk. Merging. Addresses issue #42.
2 parents dc7a95e + 4eebb44 commit 559baaf

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

_includes/JB/sort_collection

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

0 commit comments

Comments
 (0)