英文:
Golang/Revel template engine template with variable
问题
有没有办法将在Golang/Revel模板中迭代的变量传递进去?
例如,在“header.html”中,我有以下代码:
{{range .templates}}
{{template "something" .}}
{{end}}
我该如何将当前数组的索引作为模板的参数使用?我尝试嵌入另一个{{.}},就像Revel的示例中所示,但这会导致模板编译错误。这个变量会是类似于$i的东西吗?
例如,在Revel中进行迭代的方式如下:
{{range .messages}}
<p>{{.}}</p>
{{end}}
然而,我读到说.表示nil....这在Revel中是如何工作的?
英文:
Is there a way to pass a variable that was iterated over into a Golang/Revel template?
For example, in "header.html", I have
{{range .templates}}
{{template "something" .}}
{{end}}
How can I use current index from the array as an argument to template? I tried embedding another {{.}} as shown in the Revel examples, but that leads to a template compliation error. Would the variable be something like $i?
For example, iterating through in Revel is done like so
{{range .messages}}
<p>{{.}}</p>
{{end}}
However, I read that the . means nil.... how does this work in Revel?
答案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>
英文:
If I understand your question correctly, you can use the range
built-in to get the index, and then pass it to the template like this:
{{range $i, $t := .templates}}
{{template "Template.html" $i}}
{{end}}
So if the templates
variable was defined like this:
templates := []string{"One", "Two"}
and Template.html
contains:
This is from Template.html: {{ . }}<br>
Then the final output will be:
This is from Template.html: 0<br>
This is from Template.html: 1<br>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论