add paginator

This commit is contained in:
aichy126 2022-11-30 15:11:06 +08:00
parent 25908ab3c6
commit c3479b7083
2 changed files with 68 additions and 0 deletions

View File

@ -1,6 +1,8 @@
package templaterender
import (
"math"
"github.com/answerdev/answer/internal/service"
"github.com/google/wire"
)
@ -25,3 +27,57 @@ func NewTemplateRenderController(
userService: userService,
}
}
// Paginator page
// page : now page
// prepage : Number per page
// nums : Total
// Returns the contents of the page in the format of 1, 2, 3, 4, and 5. If the contents are less than 5 pages, the page number is returned
func Paginator(page, prepage int, nums int64) map[string]interface{} {
var firstpage int //前一页地址
var lastpage int //后一页地址
//根据nums总数和prepage每页数量 生成分页总数
totalpages := int(math.Ceil(float64(nums) / float64(prepage))) //page总数
if page > totalpages {
page = totalpages
}
if page <= 0 {
page = 1
}
var pages []int
switch {
case page >= totalpages-5 && totalpages > 5: //最后5页
start := totalpages - 5 + 1
firstpage = page - 1
lastpage = int(math.Min(float64(totalpages), float64(page+1)))
pages = make([]int, 5)
for i, _ := range pages {
pages[i] = start + i
}
case page >= 3 && totalpages > 5:
start := page - 3 + 1
pages = make([]int, 5)
firstpage = page - 3
for i, _ := range pages {
pages[i] = start + i
}
firstpage = page - 1
lastpage = page + 1
default:
pages = make([]int, int(math.Min(5, float64(totalpages))))
for i, _ := range pages {
pages[i] = i + 1
}
firstpage = int(math.Max(float64(1), float64(page-1)))
lastpage = page + 1
//fmt.Println(pages)
}
paginatorMap := make(map[string]interface{})
paginatorMap["pages"] = pages
paginatorMap["totalpages"] = totalpages
paginatorMap["firstpage"] = firstpage
paginatorMap["lastpage"] = lastpage
paginatorMap["currpage"] = page
return paginatorMap
}

View File

@ -0,0 +1,12 @@
package templaterender
import (
"testing"
"github.com/davecgh/go-spew/spew"
)
func TestPaginator(t *testing.T) {
list := Paginator(5, 20, 300)
spew.Dump(list)
}