Print the current index of a slice when iterating using the html/template package

1.4k views Asked by At

I try to print the current index of a slice when iterating using the html/template package with Revel but I don't get the expected result.

My action:

func (c App) Index() revel.Result {
    test_slice := []string{"t", "e", "s", "t"}

    return c.Render(test_slice)
}

My template:

{{range $i, $test_slice := .}}
    {{$i}}
{{end}}

Instead of getting 0 1 2 3,

I get DevMode RunMode currentLocale errors flash test_slice session title

What did I do wrong ?

1

There are 1 answers

0
ANisus On BEST ANSWER

I am afraid you are not iterating over the test_slice array. If you did, your code would look something like this:

package main

import (
    "os"
    "html/template"
)

const templateString = `{{range $i, $test_slice := .}}
    {{$i}}
{{end}}`

func main() {
    t, err := template.New("foo").Parse(templateString)
    if err != nil {
        panic(err)
    }

    test_slice := []string{"t", "e", "s", "t"}

    err = t.Execute(os.Stdout, test_slice)
    if err != nil {
        panic(err)
    }
}

Output:

    0

    1

    2

    3

Your code is rather iterating over a map where test_slice is just one of the values. What you see is the key names of this map, where test_slice is one of them. To make it work, you should change your template to:

{{range $i, $test_slice := .test_slice}}
    {{$i}}
{{end}}

Consider this Playground example: http://play.golang.org/p/are5JNPXt1