【问题标题】:Passing Index of Array to Template将数组索引传递给模板
【发布时间】:2019-12-31 04:10:30
【问题描述】:

如何将数组的索引传递给模板? 我知道我可以这样做来访问第一个元素:

{{ with index . 0 }}

但我需要这样做:

{{ template "mytemp" index . 0 }}

这似乎不起作用。我也试过这个没用:

{{ with index . 0 }}
  {{ template "mytemp" . }}
{{ end }}

我似乎无法弄清楚如何实现这一点。

【问题讨论】:

    标签: go go-templates


    【解决方案1】:

    您需要index 操作,您可以在the documentation 中了解更多信息。这是一个工作示例:

    package main
    
    import (
        "log"
        "os"
        "text/template"
    )
    
    type Inventory struct {
        Material []string
        Count    uint
    }
    
    func main() {
        sweaters := Inventory{[]string{"wool"}, 17}
        tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{index .Material 0}}")
        if err != nil {
            log.Fatal(err)
        }
        err = tmpl.Execute(os.Stdout, sweaters)
        if err != nil {
            log.Fatal(err)
        }
    
    }
    

    Go Playground

    【讨论】:

    • 我尝试使用原始帖子中提到的索引操作,但没有成功,今晚再次尝试,它成功了。不知道我昨晚做错了什么,但现在一切都很好,谢谢。
    【解决方案2】:

    这是另一个例子:

    package main
    
    import (
        "os"
        "text/template"
    )
    
    
    func main() {
        data:=map[string]interface{}{ "item": []interface{}{"str1","str2"}}
        tmpl, _ := template.New("test").Parse(`Some text
    {{define "mytp"}}
    {{.}}
    {{end}}
    
    {{template "mytp" index .item 0}}`)
    
        tmpl.Execute(os.Stdout, data)
    }
    

    【讨论】:

    • 我尝试使用原始帖子中提到的索引操作,但没有成功,今晚再次尝试,它成功了。不知道我昨晚做错了什么,但现在一切都很好,谢谢。
    猜你喜欢
    • 2021-03-24
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 2018-08-29
    • 2013-01-27
    • 1970-01-01
    • 2017-12-31
    相关资源
    最近更新 更多