beego的view篇

1 基本语法

go 默认使用了 {{ 和 }} 作为左右标签,也可以修改。

  • 使用 . 来访问当前位置的上下文
  • 使用 $ 来引用当前模板根级的上下文
  • 使用 $var 来访问创建的变量

模板中支持的 go 语言符号

{{"string"}} // 一般 string
{{`raw string`}} // 原始 string
{{'c'}} // byte
{{print nil}} // nil 也被支持

模板中的 pipeline

可以是上下文的变量输出,也可以是函数通过管道传递的返回值

{{. | FuncA | FuncB | FuncC}}

当 pipeline 的值等于:

  • false 或 0
  • nil 的指针或 interface
  • 长度为 0 的 array, slice, map, string

那么这个 pipeline 被认为是空

if ... else ... end

{{if pipeline}}{{end}}

if 判断时,pipeline 为空时,相当于判断为 False

this.Data["IsLogin"] = true
this.Data["IsHome"] = true
this.Data["IsAbout"] = true

支持嵌套的循环

{{if .IsHome}}
{{else}}
    {{if .IsAbout}}{{end}}
{{end}}

也可以使用 else if 进行

{{if .IsHome}}
{{else if .IsAbout}}
{{else}}
{{end}}

range ... end

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

pipeline 支持的类型为 array, slice, map, channel

range 循环内部的 . 改变为以上类型的子元素

对应的值长度为 0 时,range 不会执行,. 不会改变

pages := []struct {
    Num int
}{{10}, {20}, {30}}

this.Data["Total"] = 100
this.Data["Pages"] = pages

使用 .Num 输出子元素的 Num 属性,使用 $. 引用模板中的根级上下文

{{range .Pages}}
    {{.Num}} of {{$.Total}}
{{end}}

使用创建的变量,在这里和 go 中的 range 用法是相同的。

{{range $index, $elem := .Pages}}
    {{$index}} - {{$elem.Num}} - {{.Num}} of {{$.Total}}
{{end}}

range 也支持 else

{{range .Pages}}
{{else}}
    {{/* 当 .Pages 为空 或者 长度为 0 时会执行这里 */}}
{{end}}

with ... end

{{with pipeline}}{{end}}

with 用于重定向 pipeline

{{with .Field.NestField.SubField}}
    {{.Var}}
{{end}}

也可以对变量赋值操作

{{with $value := "My name is %s"}}
    {{printf . "slene"}}
{{end}}

with 也支持 else

{{with pipeline}}
{{else}}
    {{/* 当 pipeline 为空时会执行这里 */}}
{{end}}

define

define 可以用来定义自模板,可用于模块定义和模板嵌套

{{define "loop"}}
    <li>{{.Name}}</li>
{{end}}

使用 template 调用模板

<ul>
    {{range .Items}}
        {{template "loop" .}}
    {{end}}
</ul>

template

{{template "模板名" pipeline}}

将对应的上下文 pipeline 传给模板,才可以在模板中调用

Beego 中支持直接载入文件模板

{{template "path/to/head.html" .}}

Beego 会依据你设置的模板路径读取 head.html

在模板中可以接着载入其他模板,对于模板的分模块处理很有用处

注释

允许多行文本注释,不允许嵌套

{{/* comment content
support new line */}}

2 基本函数

变量可以使用符号 | 在函数间传递

{{.Con | markdown | addlinks}}
{{.Name | printf "%s"}}

使用括号

{{printf "nums is %s %d" (printf "%d %d" 1 2) 3}}

and

{{and .X .Y .Z}}

and 会逐一判断每个参数,将返回第一个为空的参数,否则就返回最后一个非空参数

call

{{call .Field.Func .Arg1 .Arg2}}

call 可以调用函数,并传入参数

调用的函数需要返回 1 个值 或者 2 个值,返回两个值时,第二个值用于返回 error 类型的错误。返回的错误不等于 nil 时,执行将终止。

index

index 支持 map, slice, array, string,读取指定类型对应下标的值

this.Data["Maps"] = map[string]string{"name": "Beego"}
{{index .Maps "name"}}

len

{{printf "The content length is %d" (.Content|len)}}

返回对应类型的长度,支持类型:map, slice, array, string, chan

not

not 返回输入参数的否定值,if true then false else true

or

{{or .X .Y .Z}}

or 会逐一判断每个参数,将返回第一个非空的参数,否则就返回最后一个参数

print

对应 fmt.Sprint

printf

对应 fmt.Sprintf

println

对应 fmt.Sprintln

urlquery

{{urlquery "http://beego.me"}}

得到 http%3A%2F%2Fbeego.me

eq / ne / lt / le / gt / ge

这类函数一般配合在 if 中使用

eq: arg1 == arg2 ne: arg1 != arg2 lt: arg1 < arg2 le: arg1 <= arg2 gt: arg1 > arg2 ge: arg1 >= arg2

eq 和其他函数不一样的地方是,支持多个参数,和下面的逻辑判断相同

arg1==arg2 || arg1==arg3 || arg1==arg4 ...

与 if 一起使用

{{if eq true .Var1 .Var2 .Var3}}{{end}}
{{if lt 100 200}}{{end}}

2 模板处理

beego 的模板处理引擎采用的是 Go 内置的 html/template 包进行处理,而且 beego 的模板处理逻辑是采用了缓存编译方式,也就是所有的模板会在 beego 应用启动的时候全部编译然后缓存在 map 里面。

模板目录

默认模板目录是views,可以通过配置app.conf中的viewspath,具体配置查看Beego框架 app.conf配置 ,beego 会自动在该目录下的所有模板文件进行解析并缓存,开发模式下每次都会重新解析,不做缓存。

自动渲染

通过配置autorender指定是否由go内部自动渲染

模板标签

Go 语言的默认模板采用了 {{ 和 }} 作为左右标签,若要修改参考Beego框架 app.conf配置

模板数据

模板中的数据是通过在 Controller 中 this.Data 获取的,所以如果你想在模板中获取内容 {{.Content}} ,那么你需要在 Controller 中如下设置:

this.Data["Content"] = "value"

各种类型的数据渲染:

  • 结构体

例如:

type A struct{
      Name string
      Age  int
  }

控制器数据赋值

this.Data["a"]=&A{Name:"astaxie",Age:25}

模板渲染数据如下:

the username is {{.a.Name}}
the age is {{.a.Age}}
  • map

控制器数据赋值

  mp["name"]="astaxie"
  mp["nickname"] = "haha"
  this.Data["m"]=mp

模板渲染数据如下:

  the username is {{.m.name}}
  the username is {{.m.nickname}}
  • slice

控制器数据赋值

ss :=[]string{"a","b","c"}
  this.Data["s"]=ss

模板渲染数据如下:

{{range $key, $val := .s}}
  {{$key}}
  {{$val}}
  {{end}}

模板名称

通过在 Controller 的对应方法中设置相应的模板名称,beego 会自动的在 viewpath 目录下查询该文件并渲染

this.TplName = "admin/add.tpl"

beego 默认情况下支持 tpl 和 html 后缀名的模板文件,如果你的后缀名不是这两种,请进行如下设置:

beego.AddTemplateExt("你文件的后缀名")

当你设置了自动渲染,然后在你的 Controller 中没有设置任何的 TplName,那么 beego 会自动设置你的模板文件如下:

c.TplName = strings.ToLower(c.controllerName) + "/" + strings.ToLower(c.actionName) + "." + c.TplExt

Layout 设计

beego 支持 layout 设计,例如你在管理系统中,整个管理界面是固定的,只会变化中间的部分,那么你可以通过如下的设置:

this.Layout = "admin/layout.html"
this.TplName = "admin/add.tpl"

在 layout.html 中你必须设置如下的变量:

{{.LayoutContent}}

beego 就会首先解析 TplName 指定的文件,获取内容赋值给 LayoutContent,然后最后渲染 layout.html 文件。

目前采用首先把目录下所有的文件进行缓存,所以用户还可以通过类似这样的方式实现 layout:

{{template "header.html" .}}
Logic code
{{template "footer.html" .}}

LayoutSection

对于一个复杂的 LayoutContent,其中可能包括有javascript脚本、CSS 引用等,根据惯例,通常 css 会放到 Head 元素中,javascript 脚本需要放到 body 元素的末尾,而其它内容则根据需要放在合适的位置。在 Layout 页中仅有一个 LayoutContent 是不够的。所以在 Controller 中增加了一个 LayoutSections属性,可以允许 Layout 页中设置多个 section,然后每个 section 可以分别包含各自的子模板页。

layout_blog.tpl:

<!DOCTYPE html>
<html>
<head>
    <title>Lin Li</title>
    {{.HtmlHead}}
</head>
<body>

    <div class="container">
        {{.LayoutContent}}
    </div>
    <div>
        {{.SideBar}}
    </div>
    {{.Scripts}}
</body>
</html>

html_head.tpl:

<style>
     h1 {
        color: red;
     }
</style>

scripts.tpl:

<script type="text/javascript">
    $(document).ready(function() {
        // bla bla bla
    });
</script>

逻辑处理如下所示:

type BlogsController struct {
    beego.Controller
}

func (this *BlogsController) Get() {
    this.Layout = "layout_blog.tpl"
    this.TplName = "blogs/index.tpl"
    this.LayoutSections = make(map[string]string)
    this.LayoutSections["HtmlHead"] = "blogs/html_head.tpl"
    this.LayoutSections["Scripts"] = "blogs/scripts.tpl"
    this.LayoutSections["Sidebar"] = ""
}

renderform 使用

type User struct {
    Id    int         `form:"-"`
    Name  interface{} `form:"username"`
    Age   int         `form:"age,text,年龄:"`
    Sex   string
    Intro string `form:",textarea"`
}
  • StructTag 的定义用的标签用为 form,和 ParseForm 方法 共用一个标签,标签后面有三个可选参数,用 , 分割。第一个参数为表单中类型的 name 的值,如果为空,则以 struct field name 为值。第二个参数为表单组件的类型,如果为空,则为 text。表单组件的标签默认为 struct field name 的值,否则为第三个值。
  • 如果 form 标签只有一个值,则为表单中类型 name 的值,除了最后一个值可以忽略外,其他位置的必须要有 , 号分割,如:form:",,姓名:"
  • 如果要忽略一个字段,有两种办法,一是:字段名小写开头,二是:form 标签的值设置为 -
  • 现在的代码版本只能实现固定的格式,用 br 标签实现换行,无法实现 css 和 class 等代码的插入。所以,要实现 form 的高级排版,不能使用 renderform 的方法,而需要手动处理每一个字段。

controller:

func (this *AddController) Get() {
    this.Data["Form"] = &User{}
    this.TplName = "index.tpl"
}

Form 的参数必须是一个 struct 的指针。

template:

<form action="" method="post">
{{.Form | renderform}}
</form>

上面的代码生成的表单为:

 Name: <input name="username" type="text" value="test"></br>
    年龄:<input name="age" type="text" value="0"></br>
    Sex: <input name="Sex" type="text" value=""></br>
    Intro: <input name="Intro" type="textarea" value="">

3 模板函数

beego 支持用户定义模板函数,但是必须在 `beego.Run()` 调用之前,设置如下:

    func hello(in string)(out string){
        out = in + "world"
        return
    }

    beego.AddFuncMap("hi",hello)

定义之后你就可以在模板中这样使用了:

    {{.Content | hi}}

目前 beego 内置的模板函数如下所示:

* dateformat

    实现了时间的格式化,返回字符串,使用方法 {{dateformat .Time "2006-01-02T15:04:05Z07:00"}}。

* date

    实现了类似 PHP 的 date 函数,可以很方便的根据字符串返回时间,使用方法 {{date .T "Y-m-d H:i:s"}}。

* compare

    实现了比较两个对象的比较,如果相同返回 true,否者 false,使用方法 {{compare .A .B}}。

* substr

    实现了字符串的截取,支持中文截取的完美截取,使用方法 {{substr .Str 0 30}}。

* html2str

    实现了把 html 转化为字符串,剔除一些 script、css 之类的元素,返回纯文本信息,使用方法 {{html2str .Htmlinfo}}。

* str2html

    实现了把相应的字符串当作 HTML 来输出,不转义,使用方法 {{str2html .Strhtml}}。

* htmlquote

    实现了基本的 html 字符转义,使用方法 {{htmlquote .quote}}。

* htmlunquote

    实现了基本的反转移字符,使用方法 {{htmlunquote .unquote}}。

* renderform

    根据 StructTag 直接生成对应的表单,使用方法 {{&struct | renderform}}。

* assets_css

    为css文件生成一个`<link>`标签`. `使用方法 {{assets_css src}}

* assets_js

    为js文件生成一个`<script>`标签`.`使用方法 {{assets_js src}}

* config

    获取AppConfig的值`.`使用方法 {{config configType configKey defaultValue}}`.` 可选的 configType有String,Bool,Int,Int64,Float,DIY

* map_get

    获取 `map` 的值

    用法:

        // In controller
        Data["m"] = map[string]interface{} {
            "a": 1,
            "1": map[string]float64{
                "c": 4,
            },
        }

        // In view
        {{ map_get .m "a" }} // return 1
        {{ map_get .m 1 "c" }} // return 4

* urlfor

    获取控制器方法的 URL

        {{urlfor "TestController.List"}}

    详见 模板中如何使用

4 静态文件处理

静态文件注册:

beego.SetStaticPath("/static","public")
  • 第一个参数是路径,url 路径信息
  • 第二个参数是静态文件目录(相对应用所在的目录)

beego 支持多个目录的静态文件注册,用户可以注册如下的静态文件目录。例如:

beego.SetStaticPath("/images","images")
beego.SetStaticPath("/css","css")
beego.SetStaticPath("/js","js")
  • 40
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值