Golang/Revel模板引擎模板与变量

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

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 &quot;something&quot; .}}
{{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}}
    &lt;p&gt;{{.}}&lt;/p&gt;
{{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 &quot;Template.html&quot; $i}}
{{end}}

So if the templates variable was defined like this:

templates := []string{&quot;One&quot;, &quot;Two&quot;}

and Template.html contains:

This is from Template.html: {{ . }}&lt;br&gt;

Then the final output will be:

This is from Template.html: 0&lt;br&gt;
This is from Template.html: 1&lt;br&gt;

huangapple
  • 本文由 发表于 2016年2月17日 08:41:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/35445831.html
匿名

发表评论

匿名网友

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

确定