将数组索引传递给模板

Passing Index of Array to Template

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

{{ with index . 0 }}

但我需要做这样的事情:

{{ template "mytemp" index . 0 }}

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

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

我似乎不知道如何实现这一目标。

您需要 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

这是另一个例子:

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