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.

50 lines
1.5 KiB

  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package context
  5. import (
  6. "fmt"
  7. "html/template"
  8. "net/url"
  9. "strings"
  10. "github.com/unknwon/paginater"
  11. )
  12. // Pagination provides a pagination via Paginater and additional configurations for the link params used in rendering
  13. type Pagination struct {
  14. Paginater *paginater.Paginater
  15. urlParams []string
  16. }
  17. // NewPagination creates a new instance of the Pagination struct
  18. func NewPagination(total int, page int, issueNum int, numPages int) *Pagination {
  19. p := &Pagination{}
  20. p.Paginater = paginater.New(total, page, issueNum, 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 string, ctxKey string) {
  25. _, exists := ctx.Data[ctxKey]
  26. if !exists {
  27. return
  28. }
  29. paramData := fmt.Sprintf("%v", ctx.Data[ctxKey]) // cast interface{} to string
  30. urlParam := fmt.Sprintf("%s=%v", url.QueryEscape(paramKey), url.QueryEscape(paramData))
  31. p.urlParams = append(p.urlParams, urlParam)
  32. }
  33. // GetParams returns the configured URL params
  34. func (p *Pagination) GetParams() template.URL {
  35. return template.URL(strings.Join(p.urlParams, "&"))
  36. }
  37. // SetDefaultParams sets common pagination params that are often used
  38. func (p *Pagination) SetDefaultParams(ctx *Context) {
  39. p.AddParam(ctx, "sort", "SortType")
  40. p.AddParam(ctx, "q", "Keyword")
  41. p.AddParam(ctx, "tab", "TabName")
  42. }