Files
crowsnest/cmd/frontend/Index.go

31 lines
920 B
Go
Raw Normal View History

2025-01-02 16:21:02 +01:00
package main
import (
"crowsnest/internal/model"
"html/template"
"net/http"
)
// List the latest articles using the base template.
2025-01-02 16:21:02 +01:00
func (app *App) Index(w http.ResponseWriter, req *http.Request) {
2025-01-03 01:00:06 +01:00
// get articles
articles, err := app.articles.All()
if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError); return; }
// truncate
if len(articles) > 10 {
articles = articles[:10]
}
// convert to viewmodel
2025-01-02 16:21:02 +01:00
articleVMs := make([]*model.ArticleViewModel, 0, len(articles))
for _, a := range articles {
2025-01-02 16:21:02 +01:00
articleVMs = append(articleVMs, a.ViewModel())
}
// render template
2025-01-02 15:48:55 +01:00
t := template.Must(template.ParseFiles("assets/templates/article.html", "assets/templates/layout.html"))
err = t.ExecuteTemplate(w, "base", articleVMs)
if err != nil { http.Error(w, "Failed to render template", http.StatusInternalServerError); return; }
}