Golang template
解析和创建模板
命名模板
模板没有限定扩展名,最流行的后缀是.tmpl
, vim-go提供了对它的支持,并且godoc的例子中也使用这个后缀。Atom 和 GoSublime 对.gohtml
后缀的文件提供了语法高亮的支持。通过对代码库的分析统计发现.tpl
后缀也被经常使用。当然后缀并不重要,在项目中保持清晰和一致即可。
创建模板
tpl, err := template.Parse(filename)
得到文件名为名字的模板,并保存在tpl
变量中。tpl可以被执行来显示模板。
解析多个模板
template.ParseFiles(filenames)
可以解析一组模板,使用文件名作为模板的名字。template.ParseGlob(pattern)
会根据pattern
解析所有匹配的模板并保存。
解析字符串模板
`t, err := template.New("foo").Parse(\`{ {define "T"}}Hello, { {.}}!{ {end}}`)` 可以解析字符串模板,并设置它的名字。
执行模板
执行简单模板
又两种方式执行模板。简单的模板tpl
可以通过tpl.Execute(io.Writer, data)
去执行, 模板渲染后的内容写入到io.Writer
中。Data
是传给模板的动态数据。
执行命名的模板
tpl.ExecuteTemplate(io.Writer, name, data)
和上面的简单模板类似,只不过传入了一个模板的名字,指定要渲染的模板(因为tpl
可以包含多个模板)。