How do you pass multiple objects to go template?

go, templates

Solution

You can put your more complex data into struct, and pass it just like you did `Name` and `Age`. For example,

type vars struct {
    P User
    Invoices []Invoice
}

type User struct {
    Name string
    Age int
}

type Invoice {
    Number int
    Description string
}

If you pass an instance of `vars` into the template execution, you can reference sub-structures by using dots and array indexes, just like in regular go code.

{{.P.Name}}, {{.P.Age}}, {{.Invoices[0].Number}}

Problem

Most examples I can find describe very simple/basic things, such as showing attributes of a person object like this: ``` The name is {{.Name}}. The age is {{.Age}}. ``` What happens if you have a more complicated web page, for example, multiple different objects and lists of objects, i.e. How do you do something like this: ``` {{p.Name}} is aged {{p.Age}}. Outstanding invoices {{invoices.Count}} <table> <tr><td>{{invoices[0].number}}</td></tr> .... etc... ```

Original source

Related problems