首页 > 学院 > 开发设计 > 正文

模板函数的另一种用法

2019-11-06 09:11:13
字体:
来源:转载
供稿:网友

今天遇到了一个Bug,具体如下:

type A struct{ Id int64 Title string Content string}type B struct{ a *A Num int //Num存储这a的个数信息}

此时在controller文件中this.Data["lists"]=bList,即通过模板传递[]*B形式的slice,在HTML文件中通过模板调用

{{range .lists}} //位置1 {{with .a}} //位置2 //output somrthing {{.Id}} {{.Title}} {{end}} //with结束标志 {{end}}

在上面的代码中,在位置1使用{{.Num}}可以正常显示数目;但是在位置2显示为空,改变显示方法,使用{{.Num}}显示上一级的变量。但是依然显示为空,不能正常显示。

//利用模板的变量赋值 {{range $temp := .lists}} //位置1 {{with .a}} //位置2 //output somrthing {{.Id}} {{.Title}} {{end}} //with结束标志 {{end}}

在上述代码的位置1或者位置2任意位置插入{{$temp.Num}}就可以正常显示了

总结:因为使用$.引用的是模板中的根级上下文,而不是回到上一级引用其上下级,因此使用赋值变量的方法,再显示赋值之后的temp值就可以正常显示了。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表