dongshuo5101 2015-04-21 03:00
浏览 45
已采纳

模板中数组索引的范围

I understand you can use index inside range:

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

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

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

  • drnbotxo449747 2015-04-21 03:39
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效