From 3343cacc0e5a94ca50537cb5612b5549be2d9ca0 Mon Sep 17 00:00:00 2001 From: bep Date: Fri, 6 Mar 2015 00:30:51 +0100 Subject: [PATCH] Avoid panic when pagination on 0 pages Fixes #948 --- hugolib/pagination.go | 20 ++++++++++++++++---- hugolib/pagination_test.go | 17 ++++++++++++++++- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/hugolib/pagination.go b/hugolib/pagination.go index 67cc0216..8fb4f4e4 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 7fb8fa25..5d461286 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) { -- 2.30.2