golang的一個分頁方法
阿新 • • 發佈:2018-12-22
需要做一分頁。。就做了個方法,beego裡的例子太麻煩了。還是弄個簡單的吧,上程式碼。。
html是這樣的//分頁方法,根據傳遞過來的頁數,每頁數,總數,返回分頁的內容 7個頁數 前 1,2,3,4,5 後 的格式返回,小於5頁返回具體頁數 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 }
<div class="am-cf"> 共{{.totals}}條記錄 共記{{.paginator.totalpages}} 頁 當前頁 {{.paginator.currpage}} <div class="am-fr"> <ul class="am-pagination"> <li class=""><a href="/clubadmin/topics/{{.paginator.firstpage}}">«</a></li> {{range $index,$page := .paginator.pages}} <li {{if eq $.paginator.currpage $page }}class="am-active"{{end}}><a href="/clubadmin/topics/{{$page}}">{{$page}}</a></li> {{end}} <li><a href="/clubadmin/topics/{{.paginator.lastpage}}">»</a></li> </ul> </div> </div>
controller裡是這樣的
res := models.Paginator(pa, pre_page, totals)
this.Data["paginator"] = res