模板中的数组索引范围

时间:2015-04-21 03:00:38

标签: go

我知道你可以在范围内使用索引:

{{range $i, $e := .First}}$e - {{index $.Second $i}}{{end}}

来自:how to use index inside range in html/template to iterate through parallel arrays?

如果它还包含数组,我如何对索引进行范围调整?

例如

type a struct {
   Title []string
   Article [][]string
}
IndexTmpl.ExecuteTemplate(w, "index.html", a)

的index.html

{{range $i, $a := .Title}}
  {{index $.Article $i}}  // Want to range over this.
{{end}}

1 个答案:

答案 0 :(得分:13)

您可以使用嵌套循环,就像编写代码一样。

以下是一些代码,展示了also available on the playground

package main

import (
    "html/template"
    "os"
)

type a struct {
    Title   []string
    Article [][]string
}

var data = &a{
    Title: []string{"One", "Two", "Three"},
    Article: [][]string{
        []string{"a", "b", "c"},
        []string{"d", "e"},
        []string{"f", "g", "h", "i"}},
}

var tmplSrc = `
{{range $i, $a := .Title}}
  Title: {{$a}}
  {{range $article := index $.Article $i}}
    Article: {{$article}}.
  {{end}}
{{end}}`

func main() {
    tmpl := template.Must(template.New("test").Parse(tmplSrc))
    tmpl.Execute(os.Stdout, data)
}