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

StackOverflow https://stackoverflow.com/questions/20648200

  •  19-09-2022
  •  | 
  •  

Question

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 ?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top