template包(html/template)实现了数据驱动的模板,用于生成可对抗代码注入的安全html输出。本包提供了和text/template包相同的接口,无论何时当输出是html的时候都应使用本包。
main.go
package mainimport ( html/template io/ioutil os time fmt)func main() { t := template.new(第一个模板).delims([[, ]]) //创建一个模板,设置模板边界 t, _ = t.parse(hello,[[.username]]\n) //解析模板文件 data := map[string]interface{}{username: template.html()} t.execute(os.stdout, data) //执行模板的merger操作,并输出到控制台 t2 := template.new(新的模板) //创建模板 t2.funcs(map[string]interface{}{tihuan: tihuan}) //向模板中注入函数 bytes, _ := ioutil.readfile(test2.html) //读文件 template.must(t2.parse(string(bytes))) //将字符串读作模板 t2.execute(os.stdout, map[string]interface{}{username: 你好世界}) fmt.println(\n, t2.name(), \n) t3, _ := template.parsefiles(test1.html) //将一个文件读作模板 t3.execute(os.stdout, data) fmt.println(t3.name(), \n) //模板名称 t4, _ := template.parseglob(test1.html) //将一个文件读作模板 t4.execute(os.stdout, data) fmt.println(t4.name())}//注入模板的函数func tihuan(str string) string { return str + ------- + time.now().format(2006-01-02)}
test1.html
templatehello {{.username}}
test2.html
templatehello {{.username}}
{{tihuan .username}}