1.header.tmpl
1 {{define "header"}} 2 <html> 3 <head> 4 <title>演示信息</title> 5 </head> 6 <body> 7 {{end}}
2. content.tmpl
1 {{define "content"}} 2 {{template "header"}} 3 <h1>演示嵌套</h1> 4 <ul> 5 <li>嵌套使用 define 定义子模板</li> 6 <li>调用使用 template</li> 7 </ul> 8 {{template "footer"}} 9 {{end}}
3. footer.tmpl
1 {{define "footer"}} 2 </body> 3 </html> 4 {{end}}
4. main.go
1 package main 2 3 import ( 4 "fmt" 5 "html/template" 6 "os" 7 "strings" 8 ) 9 10 type Person struct { 11 UserName string 12 Emails []string 13 Friends []*Friend 14 } 15 16 type Friend struct { 17 Fname string 18 } 19 20 func EmailDealWith(args ...interface{}) string { 21 ok := false 22 var s string 23 if len(args) == 1 { 24 s, ok = args[0].(string) 25 } 26 if !ok { 27 s = fmt.Sprint(args) 28 } 29 substrs := strings.Split(s, "@") 30 if len(substrs) != 2 { 31 return s 32 } 33 return (substrs[0] + " at" + substrs[1]) 34 } 35 36 func main() { 37 demo1() 38 demo2() 39 demo3() 40 demo4() 41 } 42 43 func demo1() { 44 t := template.New("fieldname example") 45 t, _ = t.Parse("hello {{.UserName}}!") 46 p := Person{UserName: "zhangsan"} 47 t.Execute(os.Stdout, p) 48 } 49 50 func demo2() { 51 f1 := Friend{Fname: "minux.ma"} 52 f2 := Friend{Fname: "xushiwei"} 53 t := template.New("fieldname example") 54 t = t.Funcs(template.FuncMap{"emailDeal": EmailDealWith}) // 模版函数的使用方式 55 t, _ = t.Parse(` 56 hello {{.UserName}}! 57 {{range .Emails}} 58 an email {{.|emailDeal}} 59 {{end}} 60 {{with .Friends}} 61 {{range .}} 62 my friend name is {{.Fname}} 63 {{end}} 64 {{end}} `) 65 p := Person{UserName: "Astaxie", 66 Emails: []string{"astaxie@beego.me", "astaxie@gmail.com"}, 67 Friends: []*Friend{&f1, &f2}} 68 t.Execute(os.Stdout, p) 69 } 70 71 func demo3() { 72 tEmpty := template.New("template test") 73 // Must 它的作用是检测模板是否正确,例如大括号是否匹配,注释是否正确的关闭,变量是否正确的书写 74 tEmpty = template.Must(tEmpty.Parse("空 pipeline if demo:{{if ``}}不回输出.{{end}}\n")) 75 tEmpty.Execute(os.Stdout, nil) 76 77 tWithValue := template.New("template test") 78 tWithValue = template.Must(tWithValue.Parse("不为空的 pipeline if demo: {{if `anything`}} 我有内容,我会输出. {{end}}\n")) 79 tWithValue.Execute(os.Stdout, nil) 80 81 tIfElse := template.New("template test") 82 tIfElse = template.Must(tIfElse.Parse("if-else demo:{{if `anything`}} if 部分 {{else}} else 部分.{{end}}\n")) 83 tIfElse.Execute(os.Stdout, nil) 84 } 85 86 func demo4() { 87 s1, _ := template.ParseFiles("header.tmpl", "content.tmpl", "footer.tmpl") 88 s1.ExecuteTemplate(os.Stdout, "header", nil) 89 fmt.Println() 90 s1.ExecuteTemplate(os.Stdout, "content", nil) 91 fmt.Println() 92 s1.ExecuteTemplate(os.Stdout, "footer", nil) 93 fmt.Println() 94 s1.Execute(os.Stdout, nil) 95 }
有疑问加站长微信联系(非本文作者)