Go语言中的模板(Template)是一个强大的工具,它可以让开发者在生成 HTML、XML等文本格式时,更加简单高效。Go的模板语言在设计上非常简洁,但是在功能上非常强大,它支持基本的控制流、条件语句、变量、函数等,同时还可以通过自定义函数和自定义类型等方式扩展其功能。在本文中,我们将学习Go语言中的模板,探讨其常用功能。
package main
import (
"html/template"
"os"
)
type Person struct {
Name string
Age int
}
func main() {
person := Person{Name: "Alice", Age: 20}
tmpl := `{{.Name}} is {{.Age}} years old.`
t := template.Must(template.New("person").Parse(tmpl))
err := t.Execute(os.Stdout, person)
if err != nil {
panic(err)
}
}
Alice is 20 years old.
{{.Variable}}
{{if .Condition}} ... {{else}} ... {{end}}
{{range .Array}} ... {{end}}
{{with .Variable}} ... {{end}}
{{/* 注释内容 */}}
package main
import (
"fmt"
"html/template"
"os"
"strings"
)
func main() {
funcMap := template.FuncMap{
"upper": strings.ToUpper,
}
tmpl := `{{.Name | upper}}`
t := template.Must(template.New("person").Funcs(funcMap).Parse(tmpl))
person := struct{ Name string }{"Alice"}
err := t.Execute(os.Stdout, person)
if err != nil {
panic(err)
}
}
ALICE
package main
import (
"html/template"
"os"
"strings"
)
type Person struct {
Name string
Age int
}
func main() {
funcMap := template.FuncMap{
"upper": strings.ToUpper,
}
tmpl := `
{{define "header"}}
<header>{{.Name}}'s Profile</header>
{{end}}
{{define "body"}}
<ul>
<li>Name: {{.Name}}</li>
<li>Age: {{.Age}}</li>
</ul>
{{end}}
{{template "header" .}}
{{template "body" .}}
`
t := template.Must(template.New("person").Funcs(funcMap).Parse(tmpl))
person := Person{Name: "Alice", Age: 20}
err := t.Execute(os.Stdout, person)
if err != nil {
panic(err)
}
}
<header>Alice's Profile</header>
<ul>
<li>Name: Alice</li>
<li>Age: 18</li>
</ul>
package main
import (
"html/template"
"os"
)
func main() {
tmpl := `
{{define "base"}}
<html>
<head>
<title>{{template "title" .}}</title>
</head>
<body>
{{template "content" .}}
</body>
</html>
{{end}}
{{define "title"}}{{.Name}}'s Profile{{end}}
{{define "content"}}
<ul>
<li>Name: {{.Name}}</li>
<li>Age: {{.Age}}</li>
</ul>
{{end}}
{{template "base" .}}
`
t := template.Must(template.New("person").Parse(tmpl))
person := struct {
Name string
Age int
}{"Alice", 18}
err := t.Execute(os.Stdout, person)
if err != nil {
panic(err)
}
}
<html>
<head>
<title>Alice's Profile</title>
</head>
<body>
<ul>
<li>Name: Alice</li>
<li>Age: 18</li>
</ul>
</body>
</html>