golang text/template的基本用法
下面一个例子涉及:
- 取值
- if 判断
-. 数字值判断
-. 字符串判断
-. 布尔值判断
-. 元素存在性判断 - range循环
package main
import (
"os"
"log"
"text/template"
)
const templateText = `
# GENERAL VALUE
NAME: {{.Name}}
# IF STRING
{{if ne .Name "Bob"}}No, I'm Not Bob{{end}}
# IF NUMERIC
{{- if le .Age 30}}
I am a senior one
{{else}}
I am a little one
{{end}}
# IF BOOLEAN
{{- if .Boy}}
It's a Boy
{{else}}
It's a Girl
{{end}}
# RANGE
{{- range $index, $friend := .Friends}}
Friend {{$index}}: {{$friend}}
{{- end}}
# EXISTENCE
{{- with .Gift -}}
I have a gift: {{.}}
{{else}}
I have not a gift.
{{end}}
`
func main() {
type Recipient struct {
Name string
Age int
Boy bool
Friends []string
Gift string
}
recipient := Recipient{
Name : "Jack",
Age : 30,
Friends : []string {"Bob", "Json"},
Boy : true,
}
t := template.Must(template.New("anyname").Parse(templateText))
err := t.Execute(os.Stdout, recipient)
if err != nil {
log.Println("Executing template:", err)
}
}
其中 "{{- "和" -}}"的连字符含义是是否trim前/后的空格。
运行结果:
$ go build main.go && ./main
# GENERAL
NAME: Jack
No, I'm Not Bob
# IF1
I am a senior one
# IF2
It's a Boy
# RANGE
Friend 0: Bob
Friend 1: Json
# GIFT
I have not a gift.
详细文档请参阅:https://golang.org/pkg/text/template/#pkg-examples
里面有很多高级用法,包括自定义函数等。
有疑问加站长微信联系(非本文作者)