Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range over array index in templates

Tags:

go

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}}
like image 503
user3918985 Avatar asked Apr 21 '15 03:04

user3918985


1 Answers

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)
}
like image 91
Paul Hankin Avatar answered Oct 26 '22 13:10

Paul Hankin