快速开始
func handler(w http.ResponseWriter,r *http.Request){t := template.New("new template") //创建一个模板t,err := t.ParseFile("tpl/welcome.html",nil) //解析模板文件if err != nil{ panic(err.Error())}user := GetUser() //获取用户信息t.Execute(w,user) //执行模板,并通过w输出}
各种模板
{{.}}表示当前对象,如user对象
{{.FieldName}}表示对象的某个字段
{{range …}}{{end}} go中for…range语法类似,循环
{{with …}}{{end}} 当前对象的值,上下文
//一个模板文件例子hello {{.UserName}}!{{range .Emails}}an email {{.}}{{end}}{{with .Friends}}{{range .}}my friend name is {{.Fname}}{{end}}{{end}}
{{if …}}{{else}}{{end}} go中的if-else语法类似,条件选择
//if 后只能出现bool值,不支持bool表达式if-else demo:{{if .ShowFlag}}section if {{else}}section else.{{end}}pipeline
左边的输出作为右边的输入
//当前对象作为参数,传入内置函数html中{{. | html}}
模板变量
模板使用过程中定义局部变量
{{with $x := "output"}}{{$x}}{{end}}{{with $x := "output"}}{{$x | printf "%s"}}{{end}}
输出
outputoutput
模板函数
支持的函数类型
func(args ...interface{})string
函数定义例子
func Say(args ...interface{})string{return fmt.Sprintf("%s %v","Hello",args[0])}
注册函数
t = t.Funcs(template.FuncMap{"Say":Say})
模版定义
{{Say `Func`}}{{`Pipe` | Say}}
输出:
Hello FuncHello Pipe
template中内置函数
var builtins = FuncMap{"and": and,"call": call,"html": HTMLEscaper,"index": index,"js": JSEscaper,"len": length,"not": not,"or": or,"print": fmt.Sprint,"printf": fmt.Sprintf,"println": fmt.Sprintln,"urlquery": URLQueryEscaper,}
Must操作
检测模板是否正确:大括号是否匹配,注释是否正确关闭,变量是否正确
tOk := template.New("first")template.Must(tOk.Parse(" some static text /* and a comment */"))fmt.Println("The first one parsed OK.")template.Must(template.New("second").Parse("some static text {{ .Name }}"))fmt.Println("The second one parsed OK.")fmt.Println("The next one ought to fail.")tErr := template.New("check parse error with Must")template.Must(tErr.Parse(" some static text {{ .Name }"))
输出
The first one parsed OK.The second one parsed OK.The next one ought to fail.panic: template: check parse error with Must:1: unexpected "}" in command
模板嵌套
将模版模块化,如在web开发中定义header,content,footer三个子模块
//声明{{define "module_name"}}content{{end}}//调用{{template "module_name"}}
以下定义三个文件:
- header.html
{{define "header"}}<html><head><title>演示信息</title></head><body>{{end}}
- footer.tmpl
{{define "footer"}}</body></html>{{end}}
- content.tmpl
{{define "content"}}{{template "header"}}<h1>演示嵌套</h1><ul><li>嵌套使用define定义子模板</li><li>调用使用template</li></ul>{{template "footer"}}{{end}}
go代码
ParseFiles:所有嵌套的模版全部都解析到模板中
s1,_ := template.ParseFiles("header.tmpl","content.tmpl","footer.tmpl")s1.ExecuteTemplate(w, "header",nil)s1.ExecuteTemplate(w, "footer", nil)s1.ExecuteTemplate(w, "content", nil)cle/details/79384394

