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}} + {{.Title}} - blog + {{else}} + Welcome to blog! + {{end}} + + +
Blog: Home
+ {{template "content" .}} + + diff --git a/templates/content/index.html b/templates/content/index.html new file mode 100644 index 0000000..a79b1bf --- /dev/null +++ b/templates/content/index.html @@ -0,0 +1,7 @@ +{{define "content"}} +

Hello, {{.User.Username}}!

+ + {{range .Posts}} +

{{ .User.Username }} says: {{ .Body }}

+ {{end}} +{{end}} \ No newline at end of file diff --git a/templates/index.html b/templates/index.html deleted file mode 100644 index 7598b94..0000000 --- a/templates/index.html +++ /dev/null @@ -1,16 +0,0 @@ - - - {{if .Title}} - {{.Title}} - blog - {{else}} - Welcome to blog! - {{end}} - - -

Hello, {{.Username}}!

- {{range .Posts}} -

{{ .Username }} says: {{ .Body }}

- {{end}} - - - \ No newline at end of file