diff --git a/main.go b/main.go index 418d095..be2411b 100644 --- a/main.go +++ b/main.go @@ -2,7 +2,9 @@ package main import ( "html/template" + "io/ioutil" "net/http" + "os" ) // User struct @@ -23,6 +25,41 @@ type IndexViewModel struct { Posts []Post } +// PopulateTemplates func +// Create map template name to template.Template +func PopulateTemplates() map[string]*template.Template { + const basePath = "templates" + result := make(map[string]*template.Template) + + layout := template.Must(template.ParseFiles(basePath + "/_base.html")) + dir, err := os.Open(basePath + "/content") + if err != nil { + panic("Failed to open template blocks directory: " + err.Error()) + } + fis, err := dir.Readdir(-1) + if err != nil { + panic("Failed to read contents of content directory: " + err.Error()) + } + for _, fi := range fis { + f, err := os.Open(basePath + "/content/" + fi.Name()) + if err != nil { + panic("Failed to open template '" + fi.Name() + "'") + } + content, err := ioutil.ReadAll(f) + if err != nil { + panic("Failed to read content from file '" + fi.Name() + "'") + } + f.Close() + tmpl := template.Must(layout.Clone()) + _, err = tmpl.Parse(string(content)) + if err != nil { + panic("Failed to parse contents of '" + fi.Name() + "' as template") + } + result[fi.Name()] = tmpl + } + return result +} + func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { u1 := User{Username: "bonfy"} @@ -34,8 +71,9 @@ func main() { } v := IndexViewModel{Title: "Homepage", User: u1, Posts: posts} - tpl, _ := template.ParseFiles("templates/index.html") - tpl.Execute(w, &v) + + templates := PopulateTemplates() + templates["index.html"].Execute(w, &v) }) http.ListenAndServe(":8888", nil) } diff --git a/templates/_base.html b/templates/_base.html new file mode 100644 index 0000000..3224a9b --- /dev/null +++ b/templates/_base.html @@ -0,0 +1,13 @@ + +
+ {{if .Title}} +{{ .User.Username }} says: {{ .Body }}
{{ .Username }} says: {{ .Body }}