seperate templating for routes

This commit is contained in:
Chris kerr 2024-05-27 21:16:53 -04:00
parent c0b4e92a57
commit 34fe9b4992
3 changed files with 42 additions and 29 deletions

View File

@ -1,7 +1,6 @@
package routes
import (
"html/template"
"net/http"
)
@ -10,14 +9,6 @@ func ExampleHandler(w http.ResponseWriter, r *http.Request) {
Title: "Example Page",
}
tmpl, err := template.ParseFiles("web/views/#layout.html", "web/views/example.html", "web/views/#header.html", "web/views/#footer.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = tmpl.ExecuteTemplate(w, "layout", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// Call renderTemplate with the specific template for this route
renderTemplate(w, data, "web/views/example.html")
}

View File

@ -1,27 +1,14 @@
package routes
import (
"html/template"
"net/http"
)
type PageData struct {
Title string
}
func RootHandler(w http.ResponseWriter, r *http.Request) {
data := PageData{
Title: "Home Page",
}
data := PageData{
Title: "Home Page",
}
tmpl, err := template.ParseFiles("web/views/#layout.html", "web/views/index.html", "web/views/#header.html", "web/views/#footer.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = tmpl.ExecuteTemplate(w, "layout", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// Call renderTemplate with the specific template for this route
renderTemplate(w, data, "web/views/index.html")
}

35
src/routes/template.go Normal file
View File

@ -0,0 +1,35 @@
package routes
import (
"html/template"
"net/http"
)
type PageData struct {
Title string
}
func renderTemplate(w http.ResponseWriter, data PageData, specificTemplate string) {
// List of common templates
commonTemplates := []string{
"web/views/#layout.html",
"web/views/#header.html",
"web/views/#footer.html",
}
// Append the specific template for the route
templates := append(commonTemplates, specificTemplate)
// Parse all templates
tmpl, err := template.ParseFiles(templates...)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Execute the "layout" template
err = tmpl.ExecuteTemplate(w, "layout", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}