Skip to content

Commit

Permalink
Avoid panic when pagination on 0 pages
Browse files Browse the repository at this point in the history
  • Loading branch information
bep committed Mar 5, 2015
1 parent 6e1b0e0 commit d8d2548
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
20 changes: 16 additions & 4 deletions hugolib/pagination.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ type pager struct {

type pagers []*pager

var paginatorEmptyPages Pages

type paginator struct {
paginatedPages []Pages
pagers
Expand All @@ -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]
}

Expand Down Expand Up @@ -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
}
Expand Down
17 changes: 16 additions & 1 deletion hugolib/pagination_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit d8d2548

Please sign in to comment.