企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 使用 text/template和HTML/templates包 Go为模板操作提供了丰富的支持。嵌套模板,导入函数,表示变量,迭代数据等等都很简单。如果需要比CSV数据格式更复杂的东西,模板可能是一个不错的解决方案。 模板的另一个应用是网站的页面渲染。当我们想要将服务器端数据呈现给客户端时,模板可以很好地满足要求。起初,Go模板可能会让人感到困惑。 本章将探讨如何使用模板。 ### 实践 1. 建立templates.go: ``` package templates import ( "os" "strings" "text/template" ) const sampleTemplate = ` This template demonstrates printing a {{ .Variable | printf "%#v" }}. {{if .Condition}} If condition is set, we'll print this {{else}} Otherwise, we'll print this instead {{end}} Next we'll iterate over an array of strings: {{range $index, $item := .Items}} {{$index}}: {{$item}} {{end}} We can also easily import other functions like strings.Split then immediately used the array created as a result: {{ range $index, $item := split .Words ","}} {{$index}}: {{$item}} {{end}} Blocks are a way to embed templates into one another {{ block "block_example" .}} No Block defined! {{end}} {{/* This is a way to insert a multi-line comment */}} ` const secondTemplate = ` {{ define "block_example" }} {{.OtherVariable}} {{end}} ` // RunTemplate初始化模板并展示了对模板的基本操作 func RunTemplate() error { data := struct { Condition bool Variable string Items []string Words string OtherVariable string }{ Condition: true, Variable: "variable", Items: []string{"item1", "item2", "item3"}, Words: "another_item1,another_item2,another_item3", OtherVariable: "I'm defined in a second template!", } funcmap := template.FuncMap{ "split": strings.Split, } // 这里可以链式调用 t := template.New("example") t = t.Funcs(funcmap) // 我们可以使用Must来替代它 // template.Must(t.Parse(sampleTemplate)) t, err := t.Parse(sampleTemplate) if err != nil { return err } // 为了模拟长时间操作我们通过克隆创建另一个模板 然后解析它 t2, err := t.Clone() if err != nil { return err } t2, err = t2.Parse(secondTemplate) if err != nil { return err } // 将数据填充后的模板写入标准输出 err = t2.Execute(os.Stdout, &data) if err != nil { return err } return nil } ``` 2. 建立template_files.go: ``` package templates import ( "io/ioutil" "os" "path/filepath" "text/template" ) //CreateTemplate会创建一个包含数据的模板文件 func CreateTemplate(path string, data string) error { return ioutil.WriteFile(path, []byte(data), os.FileMode(0755)) } // InitTemplates在文件夹中设置一系列的模板文件 func InitTemplates() error { tempdir, err := ioutil.TempDir("", "temp") if err != nil { return err } // 在操作完成后全部都将被删除 defer os.RemoveAll(tempdir) err = CreateTemplate(filepath.Join(tempdir, "t1.tmpl"), ` Template 1! {{ .Var1 }} {{ block "template2" .}} {{end}} {{ block "template3" .}} {{end}} `) if err != nil { return err } err = CreateTemplate(filepath.Join(tempdir, "t2.tmpl"), ` {{ define "template2"}}Template 2! {{ .Var2 }}{{end}} `) if err != nil { return err } err = CreateTemplate(filepath.Join(tempdir, "t3.tmpl"), ` {{ define "template3"}}Template 3! {{ .Var3 }}{{end}} `) if err != nil { return err } pattern := filepath.Join(tempdir, "*.tmpl") // 组合所有匹配glob的文件并将它们组合成一个模板 tmpl, err := template.ParseGlob(pattern) if err != nil { return err } // Execute函数可以运用于map和struct tmpl.Execute(os.Stdout, map[string]string{ "Var1": "Var1!!", "Var2": "Var2!!", "Var3": "Var3!!", }) return nil } ``` 3. 建立 html_templates.go: ``` package templates import ( "fmt" "html/template" "os" ) // HTMLDifferences 展示了html/template 和 text/template的一些不同 func HTMLDifferences() error { t := template.New("html") t, err := t.Parse("<h1>Hello! {{.Name}}</h1>\n") if err != nil { return err } // html/template自动转义不安全的操作,比如javascript注入 // 这会根据变量的位置不同而呈现不完全相同的结果 err = t.Execute(os.Stdout, map[string]string{"Name": "<script>alert('Can you see me?')</script>"}) if err != nil { return err } // 你也可以手动调用转义器 fmt.Println(template.JSEscaper(`example <example@example.com>`)) fmt.Println(template.HTMLEscaper(`example <example@example.com>`)) fmt.Println(template.URLQueryEscaper(`example <example@example.com>`)) return nil } ``` 4. 以上示例打印显示较长,大家可自行运行查看。 ### 说明 Go有两个模板包 - text/template和html/template。这两个包的部分函数看起来非常相似,实际功能也确实如此。通常,使用html/template来呈现网站。模板是纯文本,但变量和函数可以在大括号块内使用。 模板包还提供了处理文件的便捷方法。示例在临时目录中创建了许多模板,然后使用一行代码读取所有模板。 html/template包是对text/template包的包装。所有模板示例都对html/template包同样适用,除了import语句无需其他任何修改。HTML模板提供了上下文感知安全性的额外好处。这可以防止诸如JavaScript注入之类的事情。 模板包能够满足你对页面操作的期望。在向HTML和JavaScript发布结果时,你可以轻松组合模板,添加应用程序逻辑并确保安全性。 * * * * 学识浅薄,错误在所难免。欢迎在群中就本书提出修改意见,以飨后来者,长风拜谢。 Golang中国(211938256) beego实战(258969317) Go实践(386056972)