2016-11-25 32 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

相關問題