diff --git a/pkg/handlers/handlers.go b/pkg/handlers/handlers.go index 3703552..5cbcc2a 100644 --- a/pkg/handlers/handlers.go +++ b/pkg/handlers/handlers.go @@ -4,6 +4,7 @@ import ( "net/http" "github.com/flashl1ght/myFirstGoApp/pkg/config" + "github.com/flashl1ght/myFirstGoApp/pkg/models" "github.com/flashl1ght/myFirstGoApp/pkg/render" ) @@ -29,10 +30,17 @@ func NewHandlers(r *Repository) { // Home is the home page handler func (m *Repository) Home(w http.ResponseWriter, r *http.Request) { - render.RenderTemplate(w, "home.page.gohtml") + render.RenderTemplate(w, "home.page.gohtml", &models.TemplateData{}) } // About is the about page handler func (m *Repository) About(w http.ResponseWriter, r *http.Request) { - render.RenderTemplate(w, "about.page.gohtml") + // perform some placeholder logic + stringMap := make(map[string]string) + stringMap["message"] = "This site is under construction" + + // send the data to the template + render.RenderTemplate(w, "about.page.gohtml", &models.TemplateData{ + StringMap: stringMap, + }) } diff --git a/pkg/models/templatedata.go b/pkg/models/templatedata.go new file mode 100644 index 0000000..9fbe4df --- /dev/null +++ b/pkg/models/templatedata.go @@ -0,0 +1,13 @@ +package models + +// TemplateData holds data sent from handlers to templates +type TemplateData struct { + StringMap map[string]string + IntMap map[string]string + FloatMap map[string]float64 + Data map[string]interface{} + CSRFToken string + Flash string + Warning string + Error string +} diff --git a/pkg/render/render.go b/pkg/render/render.go index 4af6234..f859868 100644 --- a/pkg/render/render.go +++ b/pkg/render/render.go @@ -8,6 +8,7 @@ import ( "path/filepath" "github.com/flashl1ght/myFirstGoApp/pkg/config" + "github.com/flashl1ght/myFirstGoApp/pkg/models" ) var app *config.AppConfig @@ -17,8 +18,13 @@ func NewTemplates(a *config.AppConfig) { app = a } +// AddDefaultData adds data to TemplateData +func AddDefaultData(td *models.TemplateData) *models.TemplateData { + return td +} + // RenderTemplate renders templates using html/template -func RenderTemplate(w http.ResponseWriter, tmpl string) { +func RenderTemplate(w http.ResponseWriter, tmpl string, td *models.TemplateData) { // get the template cache frokm the app config templateCache := app.TemplateCache @@ -29,7 +35,9 @@ func RenderTemplate(w http.ResponseWriter, tmpl string) { buffer := new(bytes.Buffer) - _ = t.Execute(buffer, nil) + td = AddDefaultData(td) + + _ = t.Execute(buffer, td) //render the template _, err := buffer.WriteTo(w) diff --git a/templates/about.page.gohtml b/templates/about.page.gohtml index 2de996f..efaeb92 100644 --- a/templates/about.page.gohtml +++ b/templates/about.page.gohtml @@ -5,7 +5,7 @@
This is empty
+{{index .StringMap "message"}}