add pagination

This commit is contained in:
2025-01-11 05:43:13 +01:00
parent 6deacf478f
commit f083496ebc
7 changed files with 101 additions and 10 deletions

View File

@@ -4,17 +4,36 @@ import (
"crowsnest/internal/model"
"html/template"
"net/http"
"strconv"
)
// List the latest articles using the base template.
func (app *App) Index(w http.ResponseWriter, req *http.Request) {
const pageSize = 15
var limit, offset, pageId uint64 = pageSize, 0, 0
var err error
// get page number
if pageId, err = strconv.ParseUint(req.PathValue("id"), 10, 32); err == nil {
pageId--
offset = pageId * pageSize
}
// get articles
articles, err := app.articles.All(30)
articles, err := app.articles.All(int(limit), int(offset))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// get count of total articles
totalCount, err := app.articles.CountAll()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
totalCount /= pageSize
// convert to viewmodel
articleVMs := make([]*model.ArticleViewModel, 0, len(articles))
for _, a := range articles {
@@ -22,8 +41,17 @@ func (app *App) Index(w http.ResponseWriter, req *http.Request) {
}
// render template
t := template.Must(template.ParseFiles("assets/templates/article.html", "assets/templates/layout.html"))
err = t.ExecuteTemplate(w, "base", articleVMs)
t := template.Must(template.ParseFiles(
"assets/templates/article.html",
"assets/templates/layout.html",
"assets/templates/components/pagination.html"))
data := map[string]interface{}{
"SelectedNavItemArticle": true,
"ArticleVMs": &articleVMs,
"Paginations": model.NewPaginationViewModel(uint(pageId+1), totalCount+1),
}
err = t.ExecuteTemplate(w, "base", data)
if err != nil {
http.Error(w, "Failed to render template", http.StatusInternalServerError)
return

View File

@@ -23,6 +23,7 @@ func (app *App) routes() http.Handler {
// dynamic routes
mux.Handle("GET /", LoggingMiddleware(http.HandlerFunc(app.Index)))
mux.Handle("GET /page/{id}", LoggingMiddleware(http.HandlerFunc(app.Index)))
mux.Handle("POST /up/search", LoggingMiddleware(http.HandlerFunc(app.UpSearch)))
// serve files from the "static" directory