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?
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,
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With