gogo-templates

How to get a field by index in template?


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?


Solution

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