1.基本语法
1).基础标签
统一使用了 {{ 和 }} 作为左右标签
使用 . 来访问当前位置的上下文
使用 $ 来引用当前模板根级的上下文
使用 $var 来访问创建的变量
2).if … else … end
{{if 条件}}{{end}}
//else if 判断isHome是否为真,否则判断isAbout是否为真
{{if .IsHome}}
{{else if .IsAbout}}
{{else}}
{{end}}
3).range … end
“条件”支持的类型为 array, slice, map, channel
{{range 条件}}{{.}}{{end}}
使用 .Num 输出子元素的 Num 属性,使用 $. 引用模板中的根级上下文
{{range .Pages}}
{{.Num}} of {{$.Total}}
{{end}}
4).with … end
{{with pipeline}}{{end}}
**5).define **
define 可以用来定义自模板,可用于模块定义和模板嵌套
<ul>
{{range .Items}}
{{template "loop" .}}
{{end}}
</ul>
//将对应的上下文 pipeline 传给模板,才可以在模板中调用
{{template "模板名" pipeline}}
//可以直接载入文件模板
{{template "path/to/head.html" .}}
6).基础函数
//name的值输出到后面
{{.Name | printf "%s"}}
//call调用执行函数
{{call .get .param1 .param2}}
//计算name变量的长度
{{printf "%d" (.name|len)}}
2.编写模版
beego 默认情况下支持 tpl 和 html 后缀名的模板文件
1).创建模版
(1).编写模版
<!DOCTYPE html>
<html>
<head>
<title>{{.title}}</title>
</head>
<body>
{{if .showUser}}
<em>{{.useranme1}}</em><br>
{{else}}
<em>{{.username2}}</em><br>
{{end}}
{{range .users}}
<div> 用户名:{{.Username}} {{$.len}}</div>
<div> 密码:{{.Password}} {{$.len}}</div>
{{end}}
</body>
</html>
(2).编写接口
func (c *UserController) GetUser() {
println("执行get")
users := []models.User{
{Username: "test1", Password: "123456"},
{Username: "test2", Password: "123456"},
}
c.Data["title"] = "用户模版"
c.Data["showUser"] = false
c.Data["username1"] = "大旺"
c.Data["username2"] = "大兴"
c.Data["users"] = users
c.TplName = "user.tpl"
}
(3).运行后请求接口