目录
1.基本语法
模板标签{{}}
使用 .
来访问当前位置的上下文
使用 $
来引用当前模板根级的上下文
使用 $var
来访问创建的变量
if … else … end :
{{if pipeline}}
{{else if}}
{{else}}
{{end}}
eg:
this.Data["IsLogin"] = true
this.Data["IsHome"] = true
this.Data["IsAbout"] = true
{{if .IsHome}}
{{else if .IsAbout}}
{{else}}
{{end}}
range … end:语法:
{{range pipeline}}{{.}}{{end}}//pipeline 支持的类型为 array, slice, map, channel
//range 循环内部的 . 改变为以上类型的子元素
eg1:
pages := []struct {
Num int
}{{10}, {20}, {30}}
this.Data["Total"] = 100
this.Data["Pages"] = pages
//使用 .Num 输出子元素的 Num 属性,使用 $. 引用模板中的根级上下文
{{range .Pages}}
{{.Num}} of {{$.Total}}
{{end}}
eg2:
{{range $key,$val := .Pages}}
{{$key}}
{{$val}}
{{end}}
range 也支持 else
{{range .Pages}}
{{else}}
{{/* 当 .Pages 为空 或者 长度为 0 时会执行这里 */}}
{{end}}
with … end
基本函数
2.模板布局layout
controller中:
this.Layout = "admin/layout.html"
this.TplName = "admin/add.tpl"
html中:
ayout.html 中
{{.LayoutContent}}
3.模板数据
模板中的数据是通过在 Controller 中 this.Data = value
如果value是结构体类型,取属性:{{.value.属性名}}
map:{{.map.key}}
slice:
{{range $key, $val := .s}}
{{$key}}
{{$val}}
{{end}}
模板名称
4.模板中可以使用的函数
beego 支持用户定义模板函数,但是必须在 beego.Run()
调用之前,设置如下:
func hello(in string)(out string){
out = in + "world"
return
}
beego.AddFuncMap("hi",hello)
定义之后你就可以在模板中这样使用了:
{{.Content | hi}}
自带模板函数有:
compare
实现了比较两个对象的比较,如果相同返回 true,否者 false,使用方法 {{compare .A .B}}。
eg:
{{.article.Time.Format "2006-01-02 15:04:05"}}
{{if compare .TypeName $.TypeName}}selected="true"{{end}}
自定义模板函数举例:eg: