html/template包实现了数据驱动的模板,用于生成可防止代码注入的安全的HTML内容。它提供了和text/template包相同的接口,Go语言中输出HTML的场景都应使用html/template这个包。
template嵌套可以在template中嵌套其他的template。这个template可以是单独的文件,也可以是通过define定义的template。
举个例子: t.tmpl文件内容如下:
tmpl test
测试嵌套template语法
{{template "ul.tmpl"}}
{{template "ol.tmpl"}}
{{ define "ol.tmpl"}}
- 吃饭
- 睡觉
- 打豆豆
{{end}}
ul.tmpl文件内容如下:
- 注释
- 日志
- 测试
{{block "name" pipeline}} T1 {{end}}
block是定义模板{{define "name"}} T1 {{end}}和执行{{template "name" pipeline}}缩写,典型的用法是定义一组根模板,然后通过在其中重新定义块模板进行自定义。
定义一个根模板templates/base.tmpl,内容如下:
Go Templates
{{block "content" . }}{{end}}
然后定义一个templates/index.tmpl,”继承”base.tmpl:
{{template "base.tmpl"}}
{{define "content"}}
Hello world!
{{end}}
然后使用template.ParseGlob按照正则匹配规则解析模板文件,然后通过ExecuteTemplate渲染指定的模板:
func index(w http.ResponseWriter, r *http.Request){
tmpl, err := template.ParseGlob("templates*.tmpl")解析模板。


