這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
寫的比較粗糙,直接寫死連結樣式,代碼可以進一步封裝,增加一些自訂的配置項
代碼如下:
package utilsimport ("fmt""math""net/http""net/url""strconv""strings")//Pagination 分頁器type Pagination struct {Request *http.RequestTotal intPernum int}//NewPagination 建立分頁器func NewPagination(req *http.Request, total int, pernum int) *Pagination {return &Pagination{Request: req,Total: total,Pernum: pernum,}}//Pages 渲染產生html分頁標籤func (p *Pagination) Pages() string {queryParams := p.Request.URL.Query()//從當前請求中擷取pagepage := queryParams.Get("page")if page == "" {page = "1"}//將頁碼轉換成整型,以便計算pagenum, _ := strconv.Atoi(page)if pagenum == 0 {return ""}//計算總頁數var totalPageNum = int(math.Ceil(float64(p.Total) / float64(p.Pernum)))//首頁連結var firstLink string//上一頁連結var prevLink string//下一頁連結var nextLink string//末頁連結var lastLink string//中間頁碼連結var pageLinks []string//首頁和上一頁連結if pagenum > 1 {firstLink = fmt.Sprintf(`<li><a href="%s">首頁</a></li>`, p.pageURL("1"))prevLink = fmt.Sprintf(`<li><a href="%s">上一頁</a></li>`, p.pageURL(strconv.Itoa(pagenum-1)))} else {firstLink = `<li class="disabled"><a href="#">首頁</a></li>`prevLink = `<li class="disabled"><a href="#">上一頁</a></li>`}//末頁和下一頁if pagenum < totalPageNum {lastLink = fmt.Sprintf(`<li><a href="%s">末頁</a></li>`, p.pageURL(strconv.Itoa(totalPageNum)))nextLink = fmt.Sprintf(`<li><a href="%s">下一頁</a></li>`, p.pageURL(strconv.Itoa(pagenum+1)))} else {lastLink = `<li class="disabled"><a href="#">末頁</a></li>`nextLink = `<li class="disabled"><a href="#">下一頁</a></li>`}//產生中間頁碼連結pageLinks = make([]string, 0, 10)startPos := pagenum - 3endPos := pagenum + 3if startPos < 1 {endPos = endPos + int(math.Abs(float64(startPos))) + 1startPos = 1}if endPos > totalPageNum {endPos = totalPageNum}for i := startPos; i <= endPos; i++ {var s stringif i == pagenum {s = fmt.Sprintf(`<li class="active"><a href="%s">%d</a></li>`, p.pageURL(strconv.Itoa(i)), i)} else {s = fmt.Sprintf(`<li><a href="%s">%d</a></li>`, p.pageURL(strconv.Itoa(i)), i)}pageLinks = append(pageLinks, s)}return fmt.Sprintf(`<ul class="pagination">%s%s%s%s%s</ul>`, firstLink, prevLink, strings.Join(pageLinks, ""), nextLink, lastLink)}//pageURL 產生分頁urlfunc (p *Pagination) pageURL(page string) string {//基於當前url建立一個url對象u, _ := url.Parse(p.Request.URL.String())q := u.Query()q.Set("page", page)u.RawQuery = q.Encode()return u.String()}
使用方法:
package main...import "你項目的路徑/utils"import "github.com/gin-gonic/gin"import "html/template"...func main() { ... r := gin.Default() r.GET("/", func(c *gin.context){ //建立一個分頁器,一萬條資料,每頁30條 pagination := utils.NewPagination(c.Request, 10000, 30) //傳到模板中需要轉換成template.HTML類型,否則html代碼會被轉義 c.HTML(200,"你的模板",gin.H{"pages":template.HTML(pagination.Pages())}) }) }
預覽: