我发送一片articles模板.每个article结构都像:
type Article struct {
ID uint32 `db:"id" bson:"id,omitempty"`
Content string `db:"content" bson:"content"`
Author string `db:"author" bson:"author"`
...
}
Run Code Online (Sandbox Code Playgroud)
我可以articles在a中循环切片{{range $n := articles}}并获得每个切片,{{$n.Content}}但我想要的只是在标题中使用第一个(在范围循环之外).我尝试的是:
{{index .articles.Content 0}}
Run Code Online (Sandbox Code Playgroud)
但我得到:
模板文件错误:template:articles_list.tmpl:14:33:在<.articles.Content>处执行"content":无法评估类型interface {}中的字段内容
如果我只是调用
{{index .articles 0}}
Run Code Online (Sandbox Code Playgroud)
它显示了整篇文章[0]对象.
我怎样才能解决这个问题?
索引函数访问指定数组的第n个元素,因此写入
{{ index .articles.Content 0 }}
本质上是试图写 articles.Content[0]
你会想要类似的东西
{{ with $n := index .articles 0 }}{{ $n.Content }}{{ end }}
更简洁的方式是:
{{(index .articles.Content 0).Content }}
Run Code Online (Sandbox Code Playgroud)
这相当于articles[0].Content.