目录

Go Template

go 语言 Template 总结

go 语言中的 template 使用{{ }}来作为一个标识符,可以在其中插入相应的 template 支持的代码块。template 是一个模板,他所以来的数据从外部传进来。

形如:

tpl.Execute(buf, jObj.MustMap(make(map[string]interface{})))

tpl 就是我们的一个模板类,其中已经读取了我们存在本地的文件,Execute 方法传入了数据。

比如{{.text}} 那么就回去寻找传进来的这个 data,是不是含有 text 这个字段。map 就是对应的 key,struct 就是对应的成员。如果没有这个字段会出现 <no value>

几个常用的关键字

“.”

点代表着一个作用域,后面接字段名获取到相应的值。 {{.text}}就是取text这个字段的值

if 关键字

{{if .data.text0}} {{end}}

if 可以判断 bool 和 string,可以判断出是否有此字段和是否是空值

range 关键字

{{range .data.buttons}} {{.text}} {{end}}

这个含义就是遍历 data 中的 buttons 数组,然后取道每个 button 中的 text 值
想要有 index 值,可以这样:

{{ range $index,$element := .array0 }} {{$index}} {{ end }}

这里还有一些默认的函数,如 (len .data.buttons)这个可以获得这个数组的长度

一些用于比较的关键字

eq
	Returns the boolean truth of arg1 == arg2
ne
	Returns the boolean truth of arg1 != arg2
lt
	Returns the boolean truth of arg1 < arg2
le
	Returns the boolean truth of arg1 <= arg2
gt
	Returns the boolean truth of arg1 > arg2
ge
	Returns the boolean truth of arg1 >= arg2

但是使用起来很诡异,如下

{{if eq .extension.T “banner”}}{{end}}

比较符号要放到前面~~

插入函数

虽然 go 的 template 支持了一些基本函数,但是不全,我们可以自定义任意的函数来使用。

t.Funcs(template.FuncMap{
		"subtract": subtract,
	})

这样就注册了一个函数,只要写一个函数叫做 subtract 就好了

func subtract(a int, b int) int {
	return a - b
}

模板中这样使用 {{ subtract 2 1}} 这个值就是1

读取多个模板

t.ParseGlob("cfg/xml/*.tpl")

读取 cfg/xml 下所有 .tpl 结尾的模板文件