Go Template to loop (range) out comments

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

Go Template to loop (range) out comments

问题

在我的posts.html文件的末尾,我需要循环遍历Struct中的2个元素。如果没有使用range,我只能得到mysql中的最后一个条目,但是尽管上面的结构部分渲染得很好,但是当它遇到range时,HTML输出就停止了。我需要在Struct中指定只循环遍历2个元素吗?

{{range .}}
<p>{{.Name}}</p>
<p>{{.Comment}}</p>
{{end}}

这是我当前的Go代码 - http://play.golang.org/p/QMT12qfaoC

另外,我还丢失了只渲染与URL匹配的mysql数据的功能,这也需要修复。

英文:

At the end of my posts.html I need to loop over 2 elements in the Struct as without range I just get the last entry in mysql but although the rest of the structure stuff above is rendering fine the html output stops when it hits the range. Do i need to specify to only range over 2 elements in my Struct ?

{{range .}}
&lt;p&gt;{{.Name}}&lt;/p&gt;
&lt;p&gt;{{.Comment}}&lt;/p&gt;
{{end}}

Here is my current go code - http://play.golang.org/p/QMT12qfaoC

As an aside I have also lost the ability to render only mysql data matching the URL which also needs fixing.

答案1

得分: 0

你不需要在struct中指定范围,因为你只是将一个帖子传递给post.html。以下代码已经足够:

<p>{{.Name}}</p>
<p>{{.Comment}}</p>
英文:

> Do i need to specify to only range over 2 elements in my Struct ?

You don't need to range over fields in a struct, this would be enough since you are just passing one post to post.html :

&lt;p&gt;{{.Name}}&lt;/p&gt;
&lt;p&gt;{{.Comment}}&lt;/p&gt;

huangapple
  • 本文由 发表于 2015年2月21日 01:40:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/28635032.html
匿名

发表评论

匿名网友

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

确定