go语言iris go语言iris框架 使用mvc解析网页请求数据

golang的iris框架的模版如何相互引用?1.用{{}}包围go语言iris的是变量go语言iris,如 {{testName}} ,这表示把给定变量的值插入, {%%}这是块元素 在faygo里叫tag,常见的有 for , if 等
2.如何在模板中定义变量,平常我们在使用的模板的时候的常会有这样的需要,在模板中要定义一个变量以方便前端逻辑的实现,在faygo模板中定义变量需要用到标签{%set%}
使用方法
{#定义变量 newName #}
{% set newName = "hello faygo" %}
{#获取变量newName的值#}
{{newName}}
定义用 tag set 取值就是上文所提到的{{}}取值
3.在模板中调用方法
这也是一个非常常见和有用的方法,在faygo中调用方法有两种方式 ,一是在渲染模板时在faygo.Map在加入你要调用的方法 , 二是注册一个全局的方法 (在faygo里叫filter过滤器),我们分别来看一下每个方法的实现
1) 在渲染模板时加入方法(render)
//在后端render时加入方法 testFunc
rErr := ctx.Render(200, switchDir+"index.html", faygo.Map{
"TITLE":title,
"testMap":map[string]string{"aaa": "111111"},
"testFunc": func(s string) string {
return s + " this is test func"
},
})
{#前端模板中调用#}
{{ testFunc("hello") }}
结果如下
hello this is test func
这种方法适合只用于此模板一个特殊方法,在其它功能中不通用 ,那么如果想定义一个方法全局都可以使用怎么办,这里就需要注册全局方法go语言iris了(见下文)
2)注册全局方法(过滤器)
如果想定义一个方法全局都可以使用怎么办,这里就需要注册一个方法
// pongo2 注册一个全局过滤器,一般在程序启动时init中注册
//这里注册了一个名叫testFilter的过滤器,指向TestFilterFunc方法
pongo2.RegisterFilter("testFilter", TestFilterFunc)
func TestFilterFunc(in, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
a := in.String() + " this is global filter"
return pongo2.AsValue(a), nil
}
在这里我们看到TestFilterFunc方法里接收参数和返回参数的类型是pongo2.Value和pongo2.Error
在注册过滤器里方法的接收参数和返回参数是固定的这两个不能改变
的话:
All functions’ parameters types must be of either your own type or of type *pongo2.Value(no matter how many) and functions must return one value of either type *Value or your own one.
那么我们返回数据时怎么返回? 在上面例子在我们看到了 AsValue 这个方法可以将我们数据返回,我们可以返回struct,map,array,string 等
在前端调用
{{ "hello" | testFilter }}
结果:
hello this is global filter
返回结构体:
type LoginUserInfo struct {
Usernamestring `json:"username"`
Telephone string `json:"telephone"`
Emailstring `json:"email"`
Levelint`json:"level"`
}
func TestFilterFunc(in, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
userInfo := LoginUserInfo{
Username:"userA",
Telephone: "123456",
Email:"123456@test.com",
Level:1,
}
return pongo2.AsValue(userInfo), nil
}
前端使用:
{#定义一个变量接收struct数据 #}
{% set uinfo = "" | testFilter %}
{#取用户名字#}
{{ uinfo.Username }}
注意 , 如是 uinfo 只是一个struct不是struct数组([]uinfo)时在模板中不能使用{% for %}使用也不会得到任何数据
如果uinfo是struct数组 在模板中for循环时不要使用 key,val in uinfo
如果uinfo是struct数组uinfo = []userInfo{}
{#错误示例#}
{% for key,val in uinfo %}
{{val.Username}}
{% endfor %}
struct数据不能使用key,否则循环会执行,但取不到任何数据

推荐阅读