for template in templates

时间:2014-07-19 11:10:10

标签: templates loops go

我在模板中需要for循环。

for i := start; i < finish; i++ {
    // do something
}

range与准备好的数组一起使用只是一种方法,或者如何将此功能添加到模板中?

1 个答案:

答案 0 :(得分:3)

最简单的方法可能是使用range和外部函数。例如(On play):

func For(start, end int) <-chan int {
    c := make(chan int)
    go func() {
        for i := start; i < end; i++ {
            c <- i
        }
        close(c)
    }()
    return c
}

在模板中:

{{range For 0 10}}
i: {{.}}
{{end}}