gregghz
gregghz

Reputation: 3965

Looping over an array of objects in a template (Go)

I'm passing a struct (one element is an array of Category objects) to the template for rendering. In the template, I have code that looks something like this:

{.repeated section Categories}
    <p>{@}</p>
{.end}

However, each Category has a few of its own elements that I need to be able to access (Title for instance). I have tried things like {@.Title} but I can't seem to find the proper syntax for accomplishing this. How do I access members of data in an array during a loop in a template?

Upvotes: 7

Views: 5589

Answers (1)

tux21b
tux21b

Reputation: 94689

You can just write {Title}.

Whenever the template package encounters an identifier, it tries to look it up in the current object and if it doesn't find anything it tries the parent (up to the root). The @ is just there if you wan't to access the current object as a whole and not one of its attributes.

Since I'm not used to the template package either, I've created a small example:

type Category struct {
    Title string
    Count int
}

func main() {
    tmpl, _ := template.Parse(`
        {.repeated section Categories}
            <p>{Title} ({Count})</p>
        {.end}
    `, nil)
    categories := []Category{
        Category{"Foo", 3},
        Category{"Bar", 5},
    }
    tmpl.Execute(os.Stdout, map[string]interface{} {
        "Categories": categories,
    })
}

Upvotes: 7

Related Questions