1

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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

I tried using the index action as mentioned in my original post but it didn't work, tried it again tonight and it did. Not sure what I did wrong last night but all is good now thanks.
1

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

1 Comment

I tried using the index action as mentioned in my original post but it didn't work, tried it again tonight and it did. Not sure what I did wrong last night but all is good now thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.