💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[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", "<script>alert('you have been pwned')</script>") // text Hello, <script>alert('you have been pwned')</script>! ``` html/template ``` t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`) err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>") // html Hello, &lt;script&gt;alert(&#39;you have been pwned&#39;)&lt;/script&gt;! ``` ## 示例 ### 简单 demo ``` const tpl = ` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>{{.Title}}</title> </head> <body> {{range .Items}}<div>{{ . }}</div>{{else}}<div><strong>no rows</strong></div>{{end}} </body> </html>` 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 <h1>{{.PageTitle}}<h1> <ul> {{range .Todos}} {{if .Done}} <li class="done">{{.Title}}</li> {{else}} <li>{{.Title}}</li> {{end}} {{end}} </ul> ```` ### ExecuteTemplate 模板中有多个定义 login.html ``` {{define "/user/login1"}} <body> login1 </body> {{end}} {{define "/user/login2"}} <body> login2 </body> {{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 ``` ### 实例 <details> <summary>详情</summary> ``` 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]) ``` </details> <br />