Revel模板多个变量,访问其中一个变量在其他范围内。

huangapple go评论95阅读模式
英文:

Revel template multiple variables, access one inside the others range

问题

我有一个控制器传递了两个变量:

func (a App) Page() revel.Result {
    var g []*G
    ...
    return c.Render(p, g)
}

在我的.html文件中,我想要遍历g。是否可以在迭代中访问p?我试过了,但是没有成功。我的尝试如下所示:

{{range .g}}
... // 打印与g相关的内容
.p
{{end}}

它会报错can't evaluate field p in type *G

英文:

I have a controller passing two variables

func (a App) Page() revel.Result {
    var g []*G
    ...
    return c.Render(p, g)
}

in my .html I want to iterate over g. Is it possible to access p inside the iteration? I couldnt manage. My try looks like the following

{{range .g}}
... // print g related stuff
.p
{{end}}

and it throws can't evaluate field p in type *G.

答案1

得分: 1

Revel似乎使用Go的模板引擎,因此我猜你应该可以使用html/template允许的任何内容,比如变量。

{{$p := .p}}
{{range .g}}
... // 打印与g相关的内容
{{$p}}
{{end}}

更多信息请参阅文档:https://golang.org/pkg/text/template/#hdr-Variables

请注意,如果p不是映射中的键,而是结构体的字段,你可能无法访问它,因为它没有被导出。好的,我现在明白了,Revel似乎从传递给Render的参数的名称中推导出模板中的名称。

英文:

Revel seems to be using Go's template engine, therefore I guess you should be able to use whatever stuff's allowed with html/template like variables.

{{$p := .p}}
{{range .g}}
... // print g related stuff
{{$p}}
{{end}}

See documentation for more info https://golang.org/pkg/text/template/#hdr-Variables

<strike>Please note, if p is not a key in a map but a field of a struct, you won't be able to access it, i believe, since it is not exported.</strike> Ok I understand now, Revel seems to derive the names inside the template from the names of the arguments that were passed to Render.

huangapple
  • 本文由 发表于 2017年3月21日 04:51:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/42913737.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定