douzhao6584 2017-03-20 20:51
浏览 31
已采纳

显示模板多个变量,在其他范围内访问一个

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条回答 默认 最新

  • dousi1097 2017-03-20 21:22
    关注

    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

    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. Ok I understand now, Revel seems to derive the names inside the template from the names of the arguments that were passed to Render.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?