This commit is contained in:
Stephen McQuay 2015-04-29 23:45:42 -07:00
commit 9b635031a4
6 changed files with 88 additions and 0 deletions

5
gen.go Normal file
View File

@ -0,0 +1,5 @@
package main
//go:generate go get github.com/jteeuwen/go-bindata/...
//go:generate rm -f static.go
//go:generate go-bindata -o static.go -pkg=main templates/...

59
main.go Normal file
View File

@ -0,0 +1,59 @@
package main
import (
"fmt"
"os"
"strings"
"text/template"
)
type Person struct {
Name string
Age int
}
func main() {
var err error
funcMap := template.FuncMap{
"title": strings.Title,
}
base, err := Asset("templates/base.txt")
if err != nil {
panic(err)
}
tmpl, err := template.New("base").Funcs(funcMap).Parse(string(base))
templates := make(map[string]*template.Template)
templateFiles := []struct {
name string
path string
}{
{"body", "templates/body.txt"},
{"detail", "templates/detail.txt"},
{"pic", "templates/pic.txt"},
}
for _, tf := range templateFiles {
a, err := Asset(tf.path)
if err != nil {
panic(err)
}
t, err := tmpl.Clone()
if err != nil {
panic(err)
}
t, err = t.Parse(string(a))
templates[tf.name] = t
}
person := Person{"bilbo", 111}
for _, name := range []string{"body", "detail", "pic"} {
fmt.Println("--------------------------------------")
err = templates[name].Execute(os.Stdout, person)
if err != nil {
panic(err)
}
}
fmt.Println("--------------------------------------")
}

3
templates/base.txt Normal file
View File

@ -0,0 +1,3 @@
{{ define "header" }}head {{ template "title" .Name }}{{ end }}
{{ define "footer" }}foot {{ if . }}{{ . }}{{ end }} {{ end }}
{{ template "body" . }}

7
templates/body.txt Normal file
View File

@ -0,0 +1,7 @@
{{ define "body" }}
{{ template "header" . }}
body: {{ .Name | title}} is {{ .Age }} years old
{{ template "footer" .Name }}
{{ end }}
{{ define "title" }} This is {{ . }}'s body {{ end }}

7
templates/detail.txt Normal file
View File

@ -0,0 +1,7 @@
{{ define "body" }}
{{ template "header" . }}
no actual details about {{ .Name }}
{{ template "footer" }}
{{ end }}
{{ define "title" }} This is {{ . }}'s detail {{ end }}

7
templates/pic.txt Normal file
View File

@ -0,0 +1,7 @@
{{ define "body" }}
{{ template "header" . }}
pic: {{ .Name | title}} is {{ .Age }} years old
{{ template "footer" }}
{{ end }}
{{ define "title" }} This is {{ . }}'s pic {{ end }}