You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pagination.go 1.8KB

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