内容简介:golang text/template的基本用法下面一个例子涉及:其中 "{{- "和" -}}"的连字符含义是是否trim前/后的空格。
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
里面有很多高级用法,包括自定义函数等。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Release It!
Michael T. Nygard / Pragmatic Bookshelf / 2007-03-30 / USD 34.95
“Feature complete” is not the same as “production ready.” Whether it’s in Java, .NET, or Ruby on Rails, getting your application ready to ship is only half the battle. Did you design your system to......一起来看看 《Release It!》 这本书的介绍吧!