如何按索引在模板中获取字段?

huangapple go评论68阅读模式
英文:

How to get a field by index in template?

问题

我将为您翻译以下内容:

我将一个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: articles_list.tmpl:14:33: 执行
> "content" 时出错,错误信息为:无法在类型 interface {} 中评估字段 Content {}

如果我只调用

{{index .articles 0}}

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

我该如何修复这个问题?

英文:

I send a slice of articles into template. Each articlestruct is like:

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

I can loop over articles slice in a {{range $n := articles}} and get each {{$n.Content}} but what I want is to have only the first one (outside the range loop) to use in headline.
What I tried is:

{{index .articles.Content 0}}

But I get:

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

If I just invoke

{{index .articles 0}}

It shows the whole article[0] object.

How can I fix this?

答案1

得分: 11

index函数用于访问指定数组的第n个元素,因此写成{{ index .articles.Content 0 }}实际上是想要写成articles.Content[0]

你可能想要使用类似以下的方式:

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

英文:

The index function access the nth element of the specified array, so writing

{{ index .articles.Content 0 }}

is essentially trying to write articles.Content[0]

You would want something akin to

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

答案2

得分: 5

更简洁的方式是:

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

这相当于 articles[0].Content

英文:

A more concise way is:

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

Which would be the equivalent of articles[0].Content.

答案3

得分: 0

{{(index .articles 0).Content}}
英文:
{{(index .articles 0).Content}}

huangapple
  • 本文由 发表于 2016年11月25日 14:28:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/40798957.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定