Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

templates

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?

like image 261
gregghz Avatar asked May 29 '11 05:05

gregghz


1 Answers

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,
    })
}
like image 191
tux21b Avatar answered Oct 10 '22 21:10

tux21b