Browse Source

init

master
Stephen McQuay 5 years ago
commit
9b635031a4
6 changed files with 88 additions and 0 deletions
  1. +5
    -0
      gen.go
  2. +59
    -0
      main.go
  3. +3
    -0
      templates/base.txt
  4. +7
    -0
      templates/body.txt
  5. +7
    -0
      templates/detail.txt
  6. +7
    -0
      templates/pic.txt

+ 5
- 0
gen.go 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
- 0
main.go 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
- 0
templates/base.txt View File

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

+ 7
- 0
templates/body.txt 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
- 0
templates/detail.txt 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
- 0
templates/pic.txt 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 }}

Loading…
Cancel
Save