使用html/template包进行迭代时,打印切片的当前索引。

huangapple go评论146阅读模式
英文:

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

问题

我尝试使用html/template包和Revel框架进行迭代时,打印切片的当前索引,但是我没有得到预期的结果。

我的操作如下:

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

    return c.Render(test_slice)
}

我的模板如下:

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

但是我得到的结果不是0 1 2 3,而是DevMode RunMode currentLocale errors flash test_slice session title

我做错了什么?

英文:

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

得分: 2

我担心你没有遍历test_slice数组。如果你这样做了,你的代码应该是这样的:

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

输出:

0

1

2

3

你的代码实际上是在遍历一个map,其中test_slice只是其中一个值。你看到的是这个map的键名,其中test_slice是其中之一。要使其正常工作,你应该将模板更改为:

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

可以参考这个Playground示例:http://play.golang.org/p/are5JNPXt1

英文:

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

huangapple
  • 本文由 发表于 2013年12月18日 09:41:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/20648200.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定