将数组的索引传递给模板

How can I pass the index of an array to a template? I know I can do something like this to access the first element:

{{ with index . 0 }}

but I need to do something like this:

{{ template "mytemp" index . 0 }}

which doesn't seem to work. I also tried this which didn't work:

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

I can't seem to figure out how to achieve this.

You need the index action, you can read more about it in the documentation. Here is a working example:

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

Here's another example:

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