view:模板视图

目录

 

1.基本语法

2.模板布局layout

3.模板数据

模板名称

4.模板函数


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:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值