【问题标题】:How to access value of first index of array in Go templates如何访问 Go 模板中数组第一个索引的值
【发布时间】:2019-03-11 23:09:35
【问题描述】:

所以我有和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) 的正确语法是什么?

【问题讨论】:

    标签: go struct slice go-templates


    【解决方案1】:

    只需对表达式进行分组并应用.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>
    

    (末尾的&lt;nil&gt;template.Execute()返回的错误值,表示执行模板没有错误。)

    【讨论】:

    • 感谢 icza 将接受答案。必须等待 6 分钟才能让我接受它
    猜你喜欢
    • 2011-04-23
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    相关资源
    最近更新 更多