美文网首页
Golang template模版语法

Golang template模版语法

作者: pokeey | 来源:发表于2021-05-12 15:40 被阅读0次

Golang template

使用方法

解析模版建议在初始化时加载一次,否则每次调用时都加载会比较浪费性能

tmpl, err := template.New("name").Parse(...)
err = tmpl.Execute(out, data)
t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")

ExecuteTemplate定义的name,为模版名称

给模版传入参数

(*.template).Execute(out, data)

data 为穿进模版的参数

给模版传入方法

(*template).Funcs(funcMap)

加载模版

匹配模式

(*.template).ParseGlob

文件名模式

(*.template).ParseFiles

字符串

(*,template).Parse("")

转译

html转译

HTMLEscaper

javascript转译

JSEscapeString

url转译

URLQueryEscaper

模版语法

更换模版匹配符号

(*template).Delims("{{", "}}")

默认是"{{}}",但是会在vue中存在冲突

定义模版名称

{{define "index"}}

插入模版

{{template "index" .}} 此时的.插入当前上下文

去除空白符

{{- .Comment -}} 去掉前面的空白和后面的空白

定义变量

{{$admpub}}

局部变量

{{with pipeline}} 
... 
{{end}}

上下文

{{.}}指向当前上下文

方法调用

{{ . | funcname }}
{{"str" | out "%s"}} -> out("%s", "str")

预定义函数

and
{{and x y}}  -> if x then y else x  如果x为真返回y,否则返回x
not 取反
or {{or x y}} -> if x then x else y 
call {{call func 1 2}} -> func(1, 2) 
html js urlquery  转译文本escape
index {{index x 1}} -> x[1] 
print printf println 等同于golang对应函数名
len 等同于golang的len函数

遍历

{{range $Item := .Table.Items}}
...
{{.}} 此时上下文已经切换到 $Item
{{end}}

{{range .Var}}
{{.}} 
{{end}}

{{range pipeline}} 
... 
{{else}}
...
{{end}}

if

{{if .IsNormal}}...{{else if}}  ...{{else}}...{{end}}------------------------eq == ne !=lt < le <=gt >ge >=

printf

{{printf "%s" .Body}}

输出内容

相关文章

网友评论

      本文标题:Golang template模版语法

      本文链接:https://www.haomeiwen.com/subject/ktmadltx.html