html/template 基础语法


文档地址: https://godoc.org/html/template

创建一个模板

var t *template.Template
t, _ = t.Parse(``)

输出

`{{ . }}` 输出

调用结构的方法

`{{ .Say "hello }}`

模板中定义变量

`{{ $a := "模板中的变量" }}`

模板函数

t.Funcs(template.FuncMap{"test1": test1}) 注册函数
t.Funcs(template.FuncMap{"test2": test2});

{{ 函数名 }} 输出函数返回值
{{ 函数名 参数1 参数2 }}

{{ .字段	名 | 函数名 }} 以字段的值作为函数的参数

t.Parse(`{{test1}}
	{{ test2 "参数" }})
	{{.UserName | test2 }}
	`)
t.Execute(os.Stdout, Person{})

条件判断

{{ if 1 }} true  {{ else }} {{ end }}

遍历

{{ range $k, &v := .Map }}
	{{ $k }} {{ $v }}
{{ end }}

嵌套模板

{{ define "tp1" }} I'm template 1 {{ end }}
{{ define "tp2" }} I'm template 2 {{ . }} {{ end }}
{{ define "tp3" }} {{ template "tp1"}} {{ template "tp2" }} {{ end }}
{{ template "tp1" }}
{{ template "tp2" "test1" }}

{{ template "tp3" "test1" }}

内置的模板函数

{{ and 3 4 }} //如果3为真, 返回4, 否则返回3

{{ or 3 4 }} // 如果3位真, 返回3, 否则返回4

{{ call sum 1 3 5 7 }} // call 后的第一个参数的返回值必须是一个函数

{{ "<br>"|html}} // 转义文本中html的标签

{{index .Contact "qq"}} // 返回 Contact 索引为qq的值

{{ "?a=123&b="你好"|js}} //	返回用js的escape处理后的文本, 自动进行html转义

{{"hello"|len}} // 返回参数的长度

{{ not 0 }} // bool 取反

{{"你好"|print "世界"}} // fmt.Sprint 的别名

{{"你好"|printf "%d %s" 123}} // Spintf的别名

{{"你好"|println "世界"}} // Println

{{?q=关键字&p=1|urlquery}} // 进行url编码

{{ if eq 1 1}} 等于
	- eq 等于
	- ne 不等于
	- lt 
	- le 
	- gt
	- ge


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。