doujiang2643 2013-12-18 01:41
浏览 52
已采纳

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

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条回答 默认 最新

  • doujiao6116 2013-12-18 07:34
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机