Avoid panic when pagination on 0 pages

Fixes #948
This commit is contained in:
bep 2015-03-06 00:30:51 +01:00
parent 6e1b0e0c00
commit 3343cacc0e
2 changed files with 32 additions and 5 deletions

View file

@ -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))
var ps pagers
if len(split) > 0 {
ps = make(pagers, len(split))
for i := range p.paginatedPages {
pagers[i] = &pager{number: (i + 1), paginator: p}
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
}

View file

@ -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) {