沉沙
2018-08-20
来源 :
阅读 1612
评论 0
摘要:本篇教程介绍了HTML+CSS入门 template包详解,希望阅读本篇文章以后大家有所收获,帮助大家HTML+CSS入门。
本篇教程介绍了HTML+CSS入门 template包详解,希望阅读本篇文章以后大家有所收获,帮助大家HTML+CSS入门。
<
template包(html/template)实现了数据驱动的模板,用于生成可对抗代码注入的安全HTML输出。本包提供了和text/template包相同的接口,无论何时当输出是HTML的时候都应使用本包。
main.go
package main
import (
"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("<script>alert(‘you have been pwned‘)</script>")}
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
<!DOCTYPE html>
<html>
<head>
<title>template</title>
</head>
<body>
hello {{.UserName}}<br>
</body>
</html>
test2.html
<!DOCTYPE html>
<html>
<head>
<title>template</title>
</head>
<body>
hello {{.UserName}}<br>
{{tihuan .UserName}}
</body>
</html>
本文由职坐标整理发布,欢迎关注职坐标WEB前端HTML/CSS频道,获取更多HTML/CSS知识!
喜欢 | 1
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号