code.gitea.io/gitea@v1.19.3/modules/context/pagination.go (about)

     1  // Copyright 2019 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package context
     5  
     6  import (
     7  	"fmt"
     8  	"html/template"
     9  	"net/url"
    10  	"strings"
    11  
    12  	"code.gitea.io/gitea/modules/paginator"
    13  )
    14  
    15  // Pagination provides a pagination via paginator.Paginator and additional configurations for the link params used in rendering
    16  type Pagination struct {
    17  	Paginater *paginator.Paginator
    18  	urlParams []string
    19  }
    20  
    21  // NewPagination creates a new instance of the Pagination struct.
    22  // "pagingNum" is "page size" or "limit", "current" is "page"
    23  func NewPagination(total, pagingNum, current, numPages int) *Pagination {
    24  	p := &Pagination{}
    25  	p.Paginater = paginator.New(total, pagingNum, current, numPages)
    26  	return p
    27  }
    28  
    29  // AddParam adds a value from context identified by ctxKey as link param under a given paramKey
    30  func (p *Pagination) AddParam(ctx *Context, paramKey, ctxKey string) {
    31  	_, exists := ctx.Data[ctxKey]
    32  	if !exists {
    33  		return
    34  	}
    35  	paramData := fmt.Sprintf("%v", ctx.Data[ctxKey]) // cast interface{} to string
    36  	urlParam := fmt.Sprintf("%s=%v", url.QueryEscape(paramKey), url.QueryEscape(paramData))
    37  	p.urlParams = append(p.urlParams, urlParam)
    38  }
    39  
    40  // AddParamString adds a string parameter directly
    41  func (p *Pagination) AddParamString(key, value string) {
    42  	urlParam := fmt.Sprintf("%s=%v", url.QueryEscape(key), url.QueryEscape(value))
    43  	p.urlParams = append(p.urlParams, urlParam)
    44  }
    45  
    46  // GetParams returns the configured URL params
    47  func (p *Pagination) GetParams() template.URL {
    48  	return template.URL(strings.Join(p.urlParams, "&"))
    49  }
    50  
    51  // SetDefaultParams sets common pagination params that are often used
    52  func (p *Pagination) SetDefaultParams(ctx *Context) {
    53  	p.AddParam(ctx, "sort", "SortType")
    54  	p.AddParam(ctx, "q", "Keyword")
    55  	// do not add any more uncommon params here!
    56  	p.AddParam(ctx, "t", "queryType")
    57  }