go分页

Posted 黑手党老k

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go分页相关的知识,希望对你有一定的参考价值。

简单的beego分页功能代码

一个简单的beego分页小插件(源代码在最下面):

支持条件查询

支持参数保留

支持自定义css样式

支持表/视图

支持参数自定义 默认为pno

支持定义生成链接的个数

使用方式:

1)action中,引入包,然后如下使用:

复制代码
/**
 * 日志列表
 */
func (this *LogController) List() {
    pno, _ := this.GetInt("pno") //获取当前请求页
    var tlog []m.Tb_log
    var conditions string = " order by id desc" //定义日志查询条件,格式为 " and name=\'zhifeiya\' and age=12 "
    var po pager.PageOptions                                                //定义一个分页对象
    po.TableName = "tb_log"                                                 //指定分页的表名
    po.EnableFirstLastLink = true                                           //是否显示首页尾页 默认false
    po.EnablePreNexLink = true                                              //是否显示上一页下一页 默认为false
    po.Conditions = conditions                                              // 传递分页条件 默认全表
    po.Currentpage = int(pno)                                               //传递当前页数,默认为1
    po.PageSize = 20                                                        //页面大小  默认为20

    //返回分页信息,
    //第一个:为返回的当前页面数据集合,ResultSet类型
    //第二个:生成的分页链接
    //第三个:返回总记录数
    //第四个:返回总页数
    rs, pagerhtml, totalItem, _ := pager.GetPagerLinks(&po, this.Ctx)
    rs.QueryRows(&tlog)      //把当前页面的数据序列化进一个切片内
    this.Data["list"] = tlog //把当前页面的数据传递到前台
    this.Data["pagerhtml"] = pagerhtml
    this.Data["totalItem"] = totalItem
    this.Data["PageSize"] = po.PageSize
    this.TplNames = "cms/log/list.html"
}
复制代码

2)视图代码:

class="default" 是分页样式,可根据实际情况设置
  <div class="default"><span>共{{.totalItem}}记录</span>
      <div style="float:left;">{{.pagerhtml}}</div>
  </div>

效果图片:

 

  <div class="meneame"><span>共{{.totalItem}}记录</span>
      <div style="float:left;">{{.pagerhtml}}</div>
  </div>

效果图片:

分页源代码:

复制代码
package pager

/**
 * 分页功能
 * 支飞亚
 * 2014-9-1
 */
import (
    // "fmt"
    "github.com/astaxie/beego/context"
    "github.com/astaxie/beego/orm"
    html "html/template"
    con "strconv"
    "strings"
    "time"
)

type PageOptions struct {
    TableName           string //表名  -----------------[必填]
    Conditions          string //条件
    Currentpage         int    //当前页 ,默认1 每次分页,必须在前台设置新的页数,不设置始终默认1.在控制器中使用方式:cp, _ := this.GetInt("pno")   po.Currentpage = int(cp)
    PageSize            int    //页面大小,默认20
    LinkItemCount       int    //生成A标签的个数 默认10个
    Href                string //A标签的链接地址  ---------[不需要设置]
    ParamName           string //参数名称  默认是pno
    FirstPageText       string //首页文字  默认"首页"
    LastPageText        string //尾页文字  默认"尾页"
    PrePageText         string //上一页文字 默认"上一页"
    NextPageText        string //下一页文字 默认"下一页"
    EnableFirstLastLink bool   //是否启用首尾连接 默认false 建议开启
    EnablePreNexLink    bool   //是否启用上一页,下一页连接 默认false 建议开启
}

/**
 * 分页函数,适用任何表
 * 返回 总记录条数,总页数,以及当前请求的数据RawSeter,调用中需要"rs.QueryRows(&tblog)"就行了  --tblog是一个Tb_log对象
 * 参数:表名,当前页数,页面大小,条件(查询条件,格式为 " and name=\'zhifeiya\' and age=12 ")
 */
func GetPagesInfo(tableName string, currentpage int, pagesize int, conditions string) (int, int, orm.RawSeter) {
    if currentpage <= 1 {
        currentpage = 1
    }
    if pagesize == 0 {
        pagesize = 20
    }
    var rs orm.RawSeter
    o := orm.NewOrm()
    var totalItem, totalpages int = 0, 0                                                          //总条数,总页数
    o.Raw("SELECT count(*) FROM " + tableName + "  where 1>0 " + conditions).QueryRow(&totalItem) //获取总条数
    if totalItem <= pagesize {
        totalpages = 1
    } else if totalItem > pagesize {
        temp := totalItem / pagesize
        if (totalItem % pagesize) != 0 {
            temp = temp + 1
        }
        totalpages = temp
    }
    rs = o.Raw("select *  from  " + tableName + "  where id >0 " + conditions + " LIMIT " + con.Itoa((currentpage-1)*pagesize) + "," + con.Itoa(pagesize))
    return totalItem, totalpages, rs
}

/**
 * 返回总记录条数,总页数,当前页面数据,分页html
 * 根据分页选项,生成分页连接 下面是一个实例:
     func (this *MainController) Test() {
        var po util.PageOptions
        po.EnablePreNexLink = true
        po.EnableFirstLastLink = true
        po.LinkItemCount = 7
        po.TableName = "help_topic"
        cp, _ := this.GetInt("pno")
        po.Currentpage = int(cp)
        _,_,_ pager := util.GetPagerLinks(&po, this.Ctx)
        this.Data["Email"] = html.HTML(pager)
        this.TplNames = "test.html"
    }
*/
func GetPagerLinks(po *PageOptions, ctx *context.Context) (int, int, orm.RawSeter, html.HTML) {
    var str string = ""
    totalItem, totalpages, rs := GetPagesInfo(po.TableName, po.Currentpage, po.PageSize, po.Conditions)
    po = setDefault(po, totalpages)
    DealUri(po, ctx)
    if totalpages <= po.LinkItemCount {
        str = fun1(po, totalpages) //显示完全  12345678910
    } else if totalpages > po.LinkItemCount {
        if po.Currentpage < po.LinkItemCount {
            str = fun2(po, totalpages) //123456789...200
        } else {
            if po.Currentpage+po.LinkItemCount < totalpages {
                str = fun3(po, totalpages)
            } else {
                str = fun4(po, totalpages)
            }
        }
    }
    return totalItem, totalpages, rs, html.HTML(str)
}

/**
 * 处理url,目的是保存参数
 */
func DealUri(po *PageOptions, ctx *context.Context) {
    uri := ctx.Request.RequestURI
    var rs string
    if strings.Contains(uri, "?") {
        arr := strings.Split(uri, "?")
        rs = arr[0] + "?" + po.ParamName + "time=" + con.Itoa(time.Now().Second())
        arr2 := strings.Split(arr[1], "&")
        for _, v := range arr2 {
            if !strings.Contains(v, po.ParamName) {
                rs += "&" + v
            }
        }
    } else {
        rs = uri + "?" + po.ParamName + "time=" + con.Itoa(time.Now().Second())
    }
    po.Href = rs
}

/**
 * 1...197 198 199 200
 */
func fun4(po *PageOptions, totalpages int) string {
    var rs string = ""
    rs += getHeader(po, totalpages)
    rs += "<a href=\'" + po.Href + "&" + po.ParamName + "=" + con.Itoa(1) + "\'>" + con.Itoa(1) + "</a>"
    rs += "<a href=\'\'>...</a>"
    for i := totalpages - po.LinkItemCount; i <= totalpages; i++ {
        if po.Currentpage != i {
            rs += "<a href=\'" + po.Href + "&" + po.ParamName + "=" + con.Itoa(i) + "\'>" + con.Itoa(i) + "</a>"
        } else {
            rs += "<span class=\\"current\\">" + con.Itoa(i) + "</span>"
        }
    }
    rs += getFooter(po, totalpages)
    return rs

}

/**
 * 1...6 7 8 9 10 11 12  13  14 15... 200
 */
func fun3(po *PageOptions, totalpages int) string {
    var rs string = ""
    rs += getHeader(po, totalpages)
    rs += "<a href=\'" + po.Href + "&" + po.ParamName + "=" + con.Itoa(1) + "\'>" + con.Itoa(1) + "</a>"
    rs += "<a href=\'\'>...</a>"
    for i := po.Currentpage - po.LinkItemCount/2 + 1; i <= po.Currentpage+po.LinkItemCount/2-1; i++ {
        if po.Currentpage != i {
            rs += "<a href=\'" + po.Href + "&" + po.ParamName + "=" + con.Itoa(i) + "\'>" + con.Itoa(i) + "</a>"
        } else {
            rs += "<span class=\\"current\\">" + con.Itoa(i) + "</span>"
        }
    }
    rs += "<a href=\'\'>...</a>"
    rs += "<a href=\'" + po.Href + "&" + po.ParamName + "=" + con.Itoa(totalpages) + "\'>" + con.Itoa(totalpages) + "</a>"
    rs += getFooter(po, totalpages)
    return rs

}

/**
 * totalpages > po.LinkItemCount   po.Currentpage < po.LinkItemCount
 * 123456789...200
 */
func fun2(po *PageOptions, totalpages int) string {
    var rs string = ""
    rs += getHeader(po, totalpages)
    for i := 1; i <= po.LinkItemCount+1; i++ {
        if i == po.LinkItemCount {
            rs += "<a href=\\"" + po.Href + "&" + po.ParamName + "=" + con.Itoa(i) + "\\">...</a>"
        } else if i == po.LinkItemCount+1 {
            rs += "<a href=\\"" + po.Href + "&" + po.ParamName + "=" + con.Itoa(totalpages) + "\\">" + con.Itoa(totalpages) + "</a>"
        } else {
            if po.Currentpage != i {
                rs += "<a href=\'" + po.Href + "&" + po.ParamName + "=" + con.Itoa(i) + "\'>" + con.Itoa(i) + "</a>"
            } else {
                rs += "<span class=\\"current\\">" + con.Itoa(i) + "</span>"
            }
        }
    }
    rs += getFooter(po, totalpages)
    return rs
}

/**
 * totalpages <= po.LinkItemCount
 * 显示完全  12345678910
 */
func fun1(po *PageOptions, totalpages int) string {

    var rs string = ""
    rs += getHeader(po, totalpages)
    for i := 1; i <= totalpages; i++ {
        if po.Currentpage != i {
            rs += "<a href=\'" + po.Href + "&" + po.ParamName + "=" + con.Itoa(i) + "\'>" + con.Itoa(i) + "</a>"
        } else {
            rs += "<span class=\\"current\\">" + con.Itoa(i) + "</span>"
        }
    }
    rs += getFooter(po, totalpages)
    return rs
}

/**
 * 头部
 */
func getHeader(po *PageOptions, totalpages int) string {
    var rs string = "<div>"
    if po.EnableFirstLastLink { //当首页,尾页都设定的时候,就显示

        rs += "<a " + judgeDisable(po, totalpages, 0) + " href=\'" + po.Href + "&" + po.ParamName + "=" + con.Itoa(1) + "\'>" + po.FirstPageText + "</a>"
    }
    if po.EnablePreNexLink { // disabled=\\"disabled\\"
        var a int = po.Currentpage - 1
        if po.Currentpage == 1 {
            a = 1
        }
        rs += "<a " + judgeDisable(po, totalpages, 0) + " href=\'" + po.Href + "&" + po.ParamName + "=" + con.Itoa(a) + "\'>" + po.PrePageText + "</a>"
    }
    return rs
}

/**
 * 尾部
 */
func getFooter(po *PageOptions, totalpages int) string {
    var rs string = ""
    if po.EnablePreNexLink {
        var a int = po.Currentpage + 1
        if po.Currentpage == totalpages {
            a = totalpages
        }
        rs += "<a " + judgeDisable(po, totalpages, 1) + "  href=\'" + po.Href + "&" + po.ParamName + "=" + con.Itoa(a) + "\'>" + po.NextPageText + "</a>"
    }
    if po.EnableFirstLastLink { //当首页,尾页都设定的时候,就显示
        rs += "<a " + judgeDisable(po, totalpages, 1) + " href=\'" + po.Href + "&" + po.ParamName + "=" + con.Itoa(totalpages) + "\'>" + po.LastPageText + "</a>"
    }
    rs += "</div>"
    return rs
}

/**
 * 设置默认值
 */
func setDefault(po *PageOptions, totalpages int) *PageOptions {
    if len(po.FirstPageText) <= 0 {
        po.FirstPageText = "首页"
    }
    if len(po.LastPageText) <= 0 {
        po.LastPageText = "尾页"
    }
    if len(po.PrePageText) <= 0 {
        po.PrePageText = "上一页"
    }
    if len(po.NextPageText) <= 0 {
        po.NextPageText = "下一页"
    }
    if po.Currentpage >= totalpages {
        po.Currentpage = totalpages
    }
    if po.Currentpage <= 1 {
        po.Currentpage = 1
    }
    if po.LinkItemCount == 0 {
        po.LinkItemCount = 10
    }
    if po.PageSize == 0 {
        po.PageSize = 20
    }
    if len(po.ParamName) <= 0 {
        po.ParamName = "pno"
    }
    return po
}

/**
 *判断首页尾页  上一页下一页是否能用
 */
func judgeDisable(po *PageOptions, totalpages int, h_f int) string {
    var rs string = ""
    //判断头部
    if h_f == 0 {
        if po.Currentpage == 1 {
            rs = "disabled=\\"disabled\\"  style=\'pointer-events:none;\'"
        }
    } else {
        if po.Currentpage == totalpages {
            rs = "disabled=\\"disabled\\"  style=\'pointer-events:none;\'"
        }
    }
    return rs
}

以上是关于go分页的主要内容,如果未能解决你的问题,请参考以下文章

go 分页器

[Go] 通过 17 个简短代码片段,切底弄懂 channel 基础

解决go: go.mod file not found in current directory or any parent directory; see ‘go help modules‘(代码片段

modx - 当我在同上片段中使用“&documents =”参数时,分页不起作用

你知道的Go切片扩容机制可能是错的

片段被视图分页器布局切割