工具包tools/paging.go
package tools
import (
"math"
)
func CreatePaging(page, pagesize, total int64) *Paging {
if page < 1 {
page = 1
}
if pagesize < 1 {
pagesize = 10
}
page_count := math.Ceil(float64(total) / float64(pagesize))
paging := new(Paging)
paging.Page = page
paging.Pagesize = pagesize
paging.Total = total
paging.PageCount = int64(page_count)
paging.NumsCount = 7
paging.setNums()
return paging
}
type Paging struct {
Page int64 //当前页
Pagesize int64 //每页条数
Total int64 //总条数
PageCount int64 //总页数
Nums []int64 //分页序数
NumsCount int64 //总页序数
}
func (this *Paging) setNums() {
this.Nums = []int64{}
if this.PageCount == 0 {
return
}
half := math.Floor(float64(this.NumsCount) / float64(2))
begin := this.Page - int64(half)
if begin < 1 {
begin = 1
}
end := begin + this.NumsCount - 1
if end >= this.PageCount {
begin = this.PageCount - this.NumsCount + 1
if begin < 1 {
begin = 1
}
end = this.PageCount
}
for i := begin; i <= end; i++ {
this.Nums = append(this.Nums, i)
}
}
控制器中使用 controllers/test.go
package controllers
import (
"test/tools"
"strconv"
"github.com/astaxie/beego"
)
type TestController struct {
beego.Controller
}
func (this *TestController) Paging() {
page, _ := this.GetInt64("page")
pageSize, _ := this.GetInt64("pageSize")
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 10
}
this.Data["paging"] = tools.CreatePaging(page, pageSize, 365)
this.TplName = "test.html"
}
模板 views/test.html
<ul class="pagination">
<li>
<a href="?page=1&pageSize={{$.paging.Pagesize}}" class="not">«</a>
</li>
{{range $k,$v:=.paging.Nums}}
<li>
<a href="?page={{$v}}&pageSize={{$.paging.Pagesize}}" class="{{if eq $v $.paging.Page}}active{{end}}">{{$v}}</a>
</li>
{{end}}
<li>
<a href="?page={{.paging.PageCount}}&pageSize={{$.paging.Pagesize}}">»</a>
</li>
</ul>
访问 http://192.168.1.55:8080/test/paging?page=11&pageSize=10
有疑问加站长微信联系(非本文作者)