golang 分頁

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

工具包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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.