1

有没有办法将迭代的变量传递到 Golang/Revel 模板中?

例如,在“header.html”中,我有

{{range .templates}}
    {{template "something" .}}
{{end}}

如何使用数组中的当前索引作为模板的参数?我尝试嵌入另一个 {{.}},如 Revel 示例中所示,但这会导致模板编译错误。变量会类似于 $i 吗?

例如,在 Revel 中迭代是这样完成的

{{range .messages}}
    <p>{{.}}</p>
{{end}}

但是,我读到 . 意味着 nil.... 这在 Revel 中是如何工作的?

4

1 回答 1

2

如果我正确理解您的问题,您可以使用range内置获取索引,然后将其传递给模板,如下所示:

{{range $i, $t := .templates}}
   {{template "Template.html" $i}}
{{end}}

因此,如果templates变量是这样定义的:

templates := []string{"One", "Two"}

Template.html包含:

This is from Template.html: {{ . }}<br>

那么最终的输出将是:

This is from Template.html: 0<br>
This is from Template.html: 1<br>
于 2016-02-17T03:07:02.153 回答