template

最后更新于:2022-04-02 02:43:58

[TOC] > [说明](https://studygolang.com/pkgdoc) ## template - 本包是对text/template包的包装,两个包提供的模板API几无差别,可以安全的随意替换两包。 - tmpl注入安全的 语法 ``` type Template func Must(t *Template, err error) *Template // 添加name 作为key 返回一个template func New(name string) *Template // 从文件获取 func ParseFiles(filenames ...string) (*Template, error) func ParseGlob(pattern string) (*Template, error) func (t *Template) Name() string func (t *Template) Delims(left, right string) *Template func (t *Template) Funcs(funcMap FuncMap) *Template func (t *Template) Clone() (*Template, error) // 查找template func (t *Template) Lookup(name string) *Template func (t *Template) Templates() []*Template // 再添加一个template func (t *Template) New(name string) *Template func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error) // 在添加一个模板 func (t *Template) Parse(src string) (*Template, error) func (t *Template) ParseFiles(filenames ...string) (*Template, error) func (t *Template) ParseGlob(pattern string) (*Template, error) // 当前template绑定数据并输出 func (t *Template) Execute(wr io.Writer, data interface{}) error // 指定name进行绑定数据并输出 func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error ``` ## text 与 html 的template 的区别 text/template ``` t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`) err = t.ExecuteTemplate(out, "T", "") // text Hello, ! ``` html/template ``` t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`) err = t.ExecuteTemplate(out, "T", "") // html Hello, <script>alert('you have been pwned')</script>! ``` ## 示例 ### 简单 demo ``` const tpl = ` {{.Title}} {{range .Items}}
{{ . }}
{{else}}
no rows
{{end}} ` t, err := template.New("webpage").Parse(tpl) if err != nil { log.Fatal(err) } data := struct { Title string Items []string }{ Title: "My page", Items: []string{ "My photos", "My blog", }, } err = t.Execute(os.Stdout, data) ``` ### 模板说明 ``` //go data := TodoPageData{ PageTitle: "My TODO list", Todos: []Todo{ {Title: "Task 1", Done: false}, {Title: "Task 2", Done: true}, {Title: "Task 3", Done: true}, }, } //html

{{.PageTitle}}

    {{range .Todos}} {{if .Done}}
  • {{.Title}}
  • {{else}}
  • {{.Title}}
  • {{end}} {{end}}
```` ### ExecuteTemplate 模板中有多个定义 login.html ``` {{define "/user/login1"}} login1 {{end}} {{define "/user/login2"}} login2 {{end}} ``` go ``` http.HandleFunc("/user/login", func(w http.ResponseWriter, r *http.Request) { tpl, e := template.ParseFiles("login.html") if e != nil { log.Fatal(e.Error()) } tpl.ExecuteTemplate(w,"/user/login1",nil) }) ``` ## text/template ### 常用语法 ``` {{if pipeline}} T1 {{end}} {{if pipeline}} T1 {{else}} T0 {{end}} {{if pipeline}} T1 {{else if pipeline}} T0 {{end}} {{range pipeline}} T1 {{end}} {{range pipeline}} T1 {{else}} T0 {{end}} {{with pipeline}} T1 {{end}} {{with pipeline}} T1 {{else}} T0 {{end}} //Variables $variable := pipeline $variable = pipeline range $index, $element := pipeline ``` ### 实例
详情 ``` const letter = ` name:{{.Name}}, {{if .Attended}} Attended is true {{- else}} Attended is false {{- end}} {{with .Gift -}} Gift is not empty :{{.}} {{end}} {{range .Items}}---------------------------------------- A1: {{.A1}} A2: {{.A2}} {{end}} CreatedAt:{{.CreatedAt | daysAgo}} days ` // Prepare some data to insert into the template. type items struct { A1 string A2 string } type Recipient struct { Name, Gift string Attended bool CreatedAt time.Time Items []items } daysAgo :=func (t time.Time) int { //fmt.Printf("%+v",t.Unix()) return int(time.Since(t).Hours() / 24) } var recipients = []Recipient{ {"Aunt Mildred", "gift is have", true, time.Date(2012,1,1,1,1,1,1,time.UTC), []items{{ A1: "a11", A2: "a22",}, { A1: "a11", A2: "a22",}, }}, } // Create a new template and parse the letter into it. t := template.Must(template.New("letter").Funcs(template.FuncMap{"daysAgo":daysAgo}).Parse(letter)) t.Execute(os.Stdout, recipients[0]) ```

';