背景
go template 有兩個庫:
- text/template: 標準模版庫
- html/template: for html template 的庫,提供更安全的解析方式
兩個庫用法基本一樣
代碼示例
package main
import (
"os"
"text/template")
type Pet struct {
Name string
Sex string
Intact bool
Age string
Breed string
}
func main() {
dogs := []Pet{
{
Name: "Jujube",
Sex: "Female",
Intact: false,
Age: "10 months",
Breed: "German Shepherd/Pitbull",
},
{
Name: "Zephyr",
Sex: "Male",
Intact: true,
Age: "13 years, 3 months",
Breed: "German Shepherd/Border Collie",
},
}
parseString(dogs)
// parseFile(dogs)
}
func parseString(dogs []Pet) {
tmplStr := `Number of dogs: {{ . | len }}
Number of dogs: {{ len . -}}
{{ range . }}
---
Name: {{ .Name }}
Sex: {{ .Sex }} ({{ if .Intact }}intact{{ else }}fixed{{ end }})
Age: {{ .Age }}
Breed: {{ .Breed }}
{{ end }}`
tmpl, err := template.New("mytest").Parse(tmplStr)
if err != nil {
panic(err)
}
err = tmpl.Execute(os.Stdout, dogs)
if err != nil {
panic(err)
}
}
func parseFile(dogs []Pet) {
var tmplFile = "pets.tmpl"
tmpl, err := template.New(tmplFile).ParseFiles(tmplFile)
if err != nil {
panic(err)
}
err = tmpl.Execute(os.Stdout, dogs)
if err != nil {
panic(err)
}
} // end main
基本概念
Action
值替換或者控制流稱為 action僚楞,用{{}}表示:
值替換:{{ .Value }}
控制流: {{ if .Value }} true branch {{ else }} false branch {{ end }}
值替換語法和類型
用dot 逐級引用,數(shù)據(jù)類型可以是struct 的成員或者 map key
空格和換行
action 前后都可以通過-trim掉空白字符,空白字符包括空格和換行符.
注意對于 {{ range .Values }} 這樣的“控制行“也會打印出一個空行
Pipeline
值替換的結(jié)果就是一個 pipeline,原文解釋”A pipeline is a possibly chained sequence of "commands". A command is a simple value (argument) or a function or method call, possibly with multiple arguments“垂涯。官方文檔中pipeline 出現(xiàn)的示例。
{{pipeline}}
{{if pipeline}} T1 {{end}}
Arguments
就當(dāng)做函數(shù)參數(shù)即可丹皱,不必過于糾結(jié)室抽。一個示例:
.Method [Argument...]
Variables
Action中可定義變量搪哪,用于后續(xù)的 action。
{{with $x := "output" | printf "%q"}}{{$x}}{{end}}
A with action that creates and uses a variable.
Function
可以在 action 中調(diào)用調(diào)用函數(shù)
有兩種調(diào)用方法
{{ len .Values }} 按照函數(shù)名坪圾,參數(shù)的方式調(diào)用
{{ .Values | len }} 使用|來調(diào)用
函數(shù)的幾種類型
- 內(nèi)置函數(shù):列表見文檔晓折,直接調(diào)用
- 變量的成員函數(shù):用 call 命令調(diào)用
- 自定義函數(shù):通過 Funcs函數(shù)調(diào)用: template.New(tmplFile).Funcs(funcMap).ParseFiles(tmplFile)