一, template 嵌套
- package main
- import (
- "os"
- "text/template"
- )
- type title struct {
- Title string
- }
- func main(){
- header :=`{{ define "header"}}<head><meta charset="utf-8"/><title>{{ .Title }}</title></head>{{ end }}`
- page1 :=`{{ define "page1" }}<!DOCYPE html>
- <HTML>
- {{ template "header" . }}
- <body>
- this is page1
- </body>
- </HTML>
- {{ end }}
- `
- page2 :=`{{ define "page2"}}<!DOCYPE HTML>
- <HTML>
- {{ template "header" . }}
- <body>
- this is page2
- </body>
- </HTML>
- {{ end }}
- `
- var ti1 =title{"定义 page1"}
- tp1,_ :=template.New("tp1").Parse(header)
- tp1,_ = tp1.Parse(page1)
- tp1,_ = tp1.Parse(page2)
- tp1.ExecuteTemplate(os.Stdout,"page1",ti1)
- }
来源: http://www.bubuko.com/infodetail-3787480.html