Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to sort by frontmatter parameters #3022

Merged
merged 5 commits into from Feb 10, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 18 additions & 0 deletions hugolib/pageSort.go
Expand Up @@ -14,6 +14,7 @@
package hugolib

import (
"fmt"
"sort"
)

Expand Down Expand Up @@ -275,3 +276,20 @@ func (p Pages) Reverse() Pages {

return pages
}

func (p Pages) ByParam(paramsKeyStr string) Pages {
fj marked this conversation as resolved.
Show resolved Hide resolved
key := "pageSort.ByParam." + paramsKeyStr

paramsKeyComparator := func(p1, p2 *Page) bool {
v1, _ := p1.Param(paramsKeyStr)
fj marked this conversation as resolved.
Show resolved Hide resolved
v2, _ := p2.Param(paramsKeyStr)
s1 := fmt.Sprintf("%v", v1)
fj marked this conversation as resolved.
Show resolved Hide resolved
s2 := fmt.Sprintf("%v", v2)

return s1 < s2
}

pages, _ := spc.get(key, p, pageBy(paramsKeyComparator).Sort)

return pages
}
23 changes: 23 additions & 0 deletions hugolib/pageSort_test.go
Expand Up @@ -113,6 +113,26 @@ func TestPageSortReverse(t *testing.T) {
assert.True(t, probablyEqualPages(p2, p1.Reverse()))
}

func TestPageSortByParam(t *testing.T) {
unsorted := createSortTestPages(10)
firstValue, _ := unsorted[0].Param("arbitrary")
fj marked this conversation as resolved.
Show resolved Hide resolved
secondValue, _ := unsorted[1].Param("arbitrary")
lastValue, _ := unsorted[9].Param("arbitrary")

assert.Equal(t, "xyz100", firstValue)
assert.Equal(t, "xyz99", secondValue)
assert.Equal(t, "xyz91", lastValue)

sorted := unsorted.ByParam("arbitrary")
firstSortedValue, _ := sorted[0].Param("arbitrary")
secondSortedValue, _ := sorted[1].Param("arbitrary")
lastSortedValue, _ := sorted[9].Param("arbitrary")

assert.Equal(t, firstValue, firstSortedValue)
assert.Equal(t, secondValue, lastSortedValue)
assert.Equal(t, lastValue, secondSortedValue)
}

func BenchmarkSortByWeightAndReverse(b *testing.B) {

p := createSortTestPages(300)
Expand Down Expand Up @@ -154,6 +174,9 @@ func createSortTestPages(num int) Pages {
},
Site: &info,
Source: Source{File: *source.NewFile(filepath.FromSlash(fmt.Sprintf("/x/y/p%d.md", i)))},
Params: map[string]interface{}{
"arbitrary": "xyz" + fmt.Sprintf("%v", 100-i),
},
}
w := 5

Expand Down