How to get a field by index in template?
Asked Answered
C

3

6

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?

Curiosity answered 25/11, 2016 at 6:28 Comment(1)
Why is this question being downvoted?Departed
I
11

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

Irmairme answered 25/11, 2016 at 6:41 Comment(1)
Yep, that solved the problem. Though I wished there was a less verbose way to do so...Curiosity
G
5

A more concise way is:

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

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

Gass answered 31/1, 2019 at 23:16 Comment(0)
A
0
{{(index .articles 0).Content}}
Adhern answered 22/9, 2022 at 7:18 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.