diff options
author | bep <bjorn.erik.pedersen@gmail.com> | 2015-03-06 00:30:51 +0100 |
---|---|---|
committer | bep <bjorn.erik.pedersen@gmail.com> | 2015-03-06 00:48:33 +0100 |
commit | 3343cacc0e5a94ca50537cb5612b5549be2d9ca0 (patch) | |
tree | 7bb57a1dde991052f451ef58d69c651ca17c179e /hugolib | |
parent | 6e1b0e0c00ced52979b8629161e36e45d51a47e6 (diff) |
Avoid panic when pagination on 0 pages
Fixes #948
Diffstat (limited to 'hugolib')
-rw-r--r-- | hugolib/pagination.go | 20 | ||||
-rw-r--r-- | hugolib/pagination_test.go | 17 |
2 files changed, 32 insertions, 5 deletions
diff --git a/hugolib/pagination.go b/hugolib/pagination.go index 67cc02167..8fb4f4e4a 100644 --- a/hugolib/pagination.go +++ b/hugolib/pagination.go @@ -30,6 +30,8 @@ type pager struct { type pagers []*pager +var paginatorEmptyPages Pages + type paginator struct { paginatedPages []Pages pagers @@ -52,6 +54,9 @@ func (p *pager) Url() template.HTML { // Pages returns the elements on this page. func (p *pager) Pages() Pages { + if len(p.paginatedPages) == 0 { + return paginatorEmptyPages + } return p.paginatedPages[p.PageNumber()-1] } @@ -233,13 +238,20 @@ func newPaginator(pages Pages, size int, urlFactory paginationUrlFactory) (*pagi split := splitPages(pages, size) p := &paginator{total: len(pages), paginatedPages: split, size: size, paginationUrlFactory: urlFactory} - pagers := make(pagers, len(split)) - for i := range p.paginatedPages { - pagers[i] = &pager{number: (i + 1), paginator: p} + var ps pagers + + if len(split) > 0 { + ps = make(pagers, len(split)) + for i := range p.paginatedPages { + ps[i] = &pager{number: (i + 1), paginator: p} + } + } else { + ps = make(pagers, 1) + ps[0] = &pager{number: 1, paginator: p} } - p.pagers = pagers + p.pagers = ps return p, nil } diff --git a/hugolib/pagination_test.go b/hugolib/pagination_test.go index 7fb8fa251..5d4612867 100644 --- a/hugolib/pagination_test.go +++ b/hugolib/pagination_test.go @@ -76,10 +76,25 @@ func TestPagerNoPages(t *testing.T) { paginator, _ := newPaginator(pages, 5, urlFactory) paginatorPages := paginator.Pagers() - assert.Equal(t, 0, len(paginatorPages)) + assert.Equal(t, 1, len(paginatorPages)) assert.Equal(t, 0, paginator.TotalNumberOfElements()) assert.Equal(t, 5, paginator.PageSize()) assert.Equal(t, 0, paginator.TotalPages()) + + // pageOne should be nothing but the first + pageOne := paginatorPages[0] + assert.NotNil(t, pageOne.First()) + assert.False(t, pageOne.HasNext()) + assert.False(t, pageOne.HasPrev()) + assert.Nil(t, pageOne.Next()) + assert.Equal(t, 1, len(pageOne.Pagers())) + assert.Equal(t, 0, len(pageOne.Pages())) + assert.Equal(t, 0, pageOne.NumberOfElements()) + assert.Equal(t, 0, pageOne.TotalNumberOfElements()) + assert.Equal(t, 0, pageOne.TotalPages()) + assert.Equal(t, 1, pageOne.PageNumber()) + assert.Equal(t, 5, pageOne.PageSize()) + } func TestPaginationUrlFactory(t *testing.T) { |