golang 分页

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

输入图片说明

转载于:https://my.oschina.net/tongjh/blog/1800443

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值