2016-11-25 95 views
-2

我将articles分片发送到模板中。每个article结构是这样的:如何通过模板中的索引获取字段?

type Article struct { 
    ID  uint32  `db:"id" bson:"id,omitempty"` 
    Content string  `db:"content" bson:"content"` 
    Author string  `db:"author" bson:"author"` 
    ... 
} 

我可以遍历articles片在{{range $n := articles}},并得到各{{$n.Content}},但我要的是只有第一个(范围外循环)在标题中使用。 我试过是:

{{index .articles.Content 0}} 

,但我得到:

Template File Error: template: articles_list.tmpl:14:33: executing "content" at <.articles.Content>: can't evaluate field Content in type interface {}

如果我只是援引

{{index .articles 0}} 

它显示了整个文章[0]对象。

我该如何解决这个问题?

回答

4

的指数函数访问指定数组的第n个元素,所以写

{{ index .articles.Content 0 }}

基本上是试图写articles.Content[0]

你会想一些类似于

{{ with $n := index .articles 0 }}{{ $n.Content }}{{ end }}

+0

是的,这解决了这个问题。虽然我希望有一个不太冗长的方式来做到这一点...... – Karlom

相关问题