在模板中遍历数组索引

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

Range over array index in templates

问题

我了解你可以在range内部使用index:

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

来源:https://stackoverflow.com/questions/16141467/how-to-use-index-inside-range-in-html-template-to-iterate-through-parallel-array

如果索引也包含一个数组,我该如何遍历索引?

例如:

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

index.html

{{range $i, $a := .Title}}
  {{index $.Article $i}}  // 想要遍历这个数组。
{{end}}
英文:

I understand you can use index inside range:

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

From: https://stackoverflow.com/questions/16141467/how-to-use-index-inside-range-in-html-template-to-iterate-through-parallel-array

How do I range over the index if it also contains an array?

Eg.

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

得分: 37

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

这是一些演示代码,也可以在 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)
}
英文:

You can use a nested loop, just as you would if you were writing code.

Here's some code demonstrating that, 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)
}

huangapple
  • 本文由 发表于 2015年4月21日 11:00:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/29762118.html
匿名

发表评论

匿名网友

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

确定