go template example
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

59 lines
1.1 KiB

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("--------------------------------------")
}