2022-08-13 06:11:36 +00:00
|
|
|
package models
|
|
|
|
|
|
|
|
import (
|
2022-08-13 22:39:31 +00:00
|
|
|
"math"
|
2022-08-13 06:11:36 +00:00
|
|
|
"net/http"
|
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Pagination result object.
|
|
|
|
type Pagination struct {
|
|
|
|
Page int
|
|
|
|
PerPage int
|
|
|
|
Total int64
|
|
|
|
Sort string
|
|
|
|
}
|
|
|
|
|
|
|
|
// Page for Iter.
|
|
|
|
type Page struct {
|
|
|
|
Page int
|
|
|
|
IsCurrent bool
|
|
|
|
}
|
|
|
|
|
|
|
|
// Load the page from form or query parameters.
|
|
|
|
func (p *Pagination) ParsePage(r *http.Request) {
|
|
|
|
raw := r.FormValue("page")
|
|
|
|
a, err := strconv.Atoi(raw)
|
|
|
|
if err == nil {
|
2022-08-14 00:42:42 +00:00
|
|
|
if a <= 0 {
|
2022-08-13 06:11:36 +00:00
|
|
|
a = 1
|
|
|
|
}
|
|
|
|
p.Page = a
|
2022-08-14 00:42:42 +00:00
|
|
|
} else {
|
|
|
|
p.Page = 1
|
2022-08-13 06:11:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Iter the pages, for templates.
|
|
|
|
func (p *Pagination) Iter() []Page {
|
2022-08-13 22:39:31 +00:00
|
|
|
var (
|
|
|
|
pages = []Page{}
|
|
|
|
total = p.Pages()
|
|
|
|
)
|
|
|
|
for i := 1; i <= total; i++ {
|
2022-08-13 06:11:36 +00:00
|
|
|
pages = append(pages, Page{
|
|
|
|
Page: i,
|
|
|
|
IsCurrent: i == p.Page,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
return pages
|
|
|
|
}
|
|
|
|
|
2022-08-13 22:39:31 +00:00
|
|
|
func (p *Pagination) Pages() int {
|
|
|
|
return int(math.Ceil(float64(p.Total) / float64(p.PerPage)))
|
|
|
|
}
|
|
|
|
|
2022-08-13 06:11:36 +00:00
|
|
|
func (p *Pagination) GetOffset() int {
|
|
|
|
return (p.Page - 1) * p.PerPage
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Pagination) HasNext() bool {
|
2022-08-13 22:39:31 +00:00
|
|
|
return p.Page < p.Pages()
|
2022-08-13 06:11:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Pagination) HasPrevious() bool {
|
|
|
|
return p.Page > 1
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Pagination) Next() int {
|
2022-08-13 22:39:31 +00:00
|
|
|
if p.Page >= p.Pages() {
|
|
|
|
return p.Pages()
|
2022-08-13 06:11:36 +00:00
|
|
|
}
|
|
|
|
return p.Page + 1
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Pagination) Previous() int {
|
|
|
|
if p.Page > 1 {
|
|
|
|
return p.Page - 1
|
|
|
|
}
|
|
|
|
return 1
|
|
|
|
}
|