2016-11-25 8 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"` 
    ... 
} 

私は{{range $n := articles}}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 {}

私はちょうどそれが全体の記事[0]オブジェクトを示し

{{index .articles 0}} 

起動した場合。

どうすればこの問題を解決できますか?

答えて

4

指数関数アクセス指定された配列のn番目の要素、そう

{{ index .articles.Content 0 }}

を書くことは、本質的にあなたが

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

に似て何かをしたいと思う articles.Content[0]

を書き込もうとしています

+0

うん、それは問題を解決した。私はそれほど冗長な方法はないと思ったが... – Karlom

関連する問題