如何在 Go 模板中访问数组第一个索引的值

How to access value of first index of array in Go templates

所以我有 html 模板,当使用它时我得到了对象:

<div>Foobar {{ index .Doc.Users 0}}</div>

输出:

<div>Foobar {MyName my@email.com}</div>

我只想使用 Name 字段我已经尝试了很多迭代都没有成功:

{{ index .Doc.Users.Name 0}}
{{ index .Doc.Users 0 .Name}}
{{ .Name index .Quote.Clients 0}}
...

仅获取数组中第一个元素的 .Name 字段 (.Doc.Users[0].Name) 的正确语法是什么?

只需将表达式分组并应用 .Name 选择器:

<div>Foobar {{ (index .Doc.Users 0).Name }}</div>

这是一个可运行、可验证的示例:

type User struct {
    Name  string
    Email string
}

t := template.Must(template.New("").Parse(
    `<div>Foobar {{ (index .Doc.Users 0).Name }}</div>`))

m := map[string]interface{}{
    "Doc": map[string]interface{}{
        "Users": []User{
            {Name: "Bob", Email: "bob@myco.com"},
            {Name: "Alice", Email: "alice@myco.com"},
        },
    },
}

fmt.Println(t.Execute(os.Stdout, m))

输出(在 Go Playground 上尝试):

<div>Foobar Bob</div><nil>

(最后的<nil>template.Execute()返回的错误值,说明执行模板没有错误。)