英文:
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 .}}
<p>{{.Name}}</p>
<p>{{.Comment}}</p>
{{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
:
<p>{{.Name}}</p>
<p>{{.Comment}}</p>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论