Skip to content

Commit

Permalink
03-Template-Advance template inheritance
Browse files Browse the repository at this point in the history
  • Loading branch information
bonfy committed Sep 7, 2018
1 parent 134267d commit e5fd3ef
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 18 deletions.
42 changes: 40 additions & 2 deletions main.go
Expand Up @@ -2,7 +2,9 @@ package main

import (
"html/template"
"io/ioutil"
"net/http"
"os"
)

// User struct
Expand All @@ -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()

This comment has been minimized.

Copy link
@AaronWharton

AaronWharton Dec 1, 2018

hello ,作者。我有个小小的建议,在 for 循环中使用 func () {}() 来包装里面文件操作的代码,保证使用 defer 不会产生延迟关闭文件的情况发生。具体可以查看 PR #bonfy/go-mega#2

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"}
Expand All @@ -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)
}
13 changes: 13 additions & 0 deletions templates/_base.html
@@ -0,0 +1,13 @@
<html>
<head>
{{if .Title}}
<title>{{.Title}} - blog</title>
{{else}}
<title>Welcome to blog!</title>
{{end}}
</head>
<body>
<div>Blog: <a href="/">Home</a></div>
{{template "content" .}}
</body>
</html>
7 changes: 7 additions & 0 deletions templates/content/index.html
@@ -0,0 +1,7 @@
{{define "content"}}
<h1>Hello, {{.User.Username}}!</h1>

{{range .Posts}}
<div><p>{{ .User.Username }} says: <b>{{ .Body }}</b></p></div>
{{end}}
{{end}}
16 changes: 0 additions & 16 deletions templates/index.html

This file was deleted.

0 comments on commit e5fd3ef

Please sign in to comment.