2025-01-02 16:21:02 +01:00
|
|
|
package main
|
2025-01-02 15:05:20 +01:00
|
|
|
|
|
|
|
|
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; }
|
2025-01-02 15:05:20 +01:00
|
|
|
|
|
|
|
|
// 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))
|
2025-01-02 15:05:20 +01:00
|
|
|
for _, a := range articles {
|
2025-01-02 16:21:02 +01:00
|
|
|
articleVMs = append(articleVMs, a.ViewModel())
|
2025-01-02 15:05:20 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// render template
|
2025-01-02 15:48:55 +01:00
|
|
|
t := template.Must(template.ParseFiles("assets/templates/article.html", "assets/templates/layout.html"))
|
2025-01-02 15:05:20 +01:00
|
|
|
err = t.ExecuteTemplate(w, "base", articleVMs)
|
|
|
|
|
if err != nil { http.Error(w, "Failed to render template", http.StatusInternalServerError); return; }
|
|
|
|
|
}
|