這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
工具包tools/paging.go
package toolsimport ("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 = pagepaging.Pagesize = pagesizepaging.Total = totalpaging.PageCount = int64(page_count)paging.NumsCount = 7paging.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 - 1if end >= this.PageCount {begin = this.PageCount - this.NumsCount + 1if begin < 1 {begin = 1}end = this.PageCount}for i := begin; i <= end; i++ {this.Nums = append(this.Nums, i)}}
控制器中使用 controllers/test.go
package controllersimport ("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