【问题标题】:How to get a field by index in template?如何通过模板中的索引获取字段?
【发布时间】:2017-04-09 11:58:09
【问题描述】:

我将articles 的一部分发送到模板中。每个articlestruct 就像:

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}}

但我明白了:

模板文件错误:模板:articles_list.tmpl:14:33:正在执行 <.articles.content> 处的“内容”:无法评估类型中的字段内容 界面{}

如果我只是调用

{{index .articles 0}}

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

我该如何解决这个问题?

【问题讨论】:

  • 为什么这个问题被否决了?

标签: go go-templates


【解决方案1】:

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

{{ index .articles.Content 0 }}

本质上是想写articles.Content[0]

你会想要类似的东西

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

【讨论】:

  • 是的,这解决了问题。虽然我希望有一种不那么冗长的方式来做到这一点......
【解决方案2】:

更简洁的方式是:

{{(index .articles.Content 0).Content }}

相当于articles[0].Content

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多