参考资料
https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/07.4.md
字段处理
示例
package main
import (
"os"
"html/template"
)
type Person struct {
UserName string
Age int
}
func main() {
t := template.New("filedname example")
t,_ = t.Parse("Hello {{ .UserName }} {{ .Age }}!")
p := Person{UserName: "victor", Age: 18}
t.Execute(os.Stdout, p)
}
// 执行结果
Hello victor 18!
输出嵌套字段内容
我们可以使用{{with ...}}...{{end}}
和 {{range ...}}{{end}}
来进行数据的输出。
package main
import (
"html/template"
"os"
)
type Friend struct {
Fname string
}
type Person struct {
UserName string
Emails []string
Friend []*Friend
}
func main() {
f1 := Friend{Fname: "Vic", }
f2 := Friend{Fname: "Tom", }
t := template.New("fieldname example")
t,_ = t.Parse(`hello {{ .UserName }}!
{{ range .Emails}}
an email {{ . }}
{{ end }}
{{with .Friends}}
{{range .}}
my friend name is {{.Fname}}
{{end}}
{{end}}
`)
p := Person{UserName: "Vic",
Emails: []string{"Vic@me.me", "Tom@me.me"},
Friend: []*Friend{&f1, &f2}}
t.Execute(os.Stdout, p)
}
// 执行结果
hello Vic!
an email Vic@me.me
an email Tom@me.me
pipelines
Unix用户已经很熟悉什么是 pipe 了, ls | grep “beego” 类似这样的语法你是不是经常使用
{{. | html}}
模板变量
$variable := pipeline
示例
{{with $x := "output" | printf "%q"}}{{$x}}{{end}}
{{with $x := "output"}}{{printf "%q" $x}}{{end}}
{{with $x := "output"}}{{$x | printf "%q"}}{{end}}
嵌套模板
Go语言中通过如下的语法来申明
{{define "子模板名称"}}内容{{end}}
通过如下方式来调用
{{template "子模板名称"}}
我们定义三个文
件, header.tmpl 、 content.tmpl 、 footer.tmpl 文件,里面的内容如下
//header.tmpl
{{define "header"}}
<html>
<head>
<title>演示信息</title>
</head>
<body>
{{end}}
//content.tmpl
{{define "content"}}
{{template "header"}}
<h1>演示嵌套</h1>
<ul>
<li>嵌套使用define定义子模板</li>
<li>调用使用template</li>
</ul>
{{template "footer"}}
{{end}}
//footer.tmpl
{{define "footer"}}
</body>
</html>
{{end}}