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

I pass the structure (one element - 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, in each category there are several own elements that I need to have access to (for example, Title). I tried things like {@ .Title}, but I cannot find the correct syntax for this. How to access data elements in an array during a loop in a template?

+7
source share
1 answer

You can simply write {Title} .

Whenever a template package encounters an identifier, it tries to find it in the current object and, if it does not find anything, it tries to create the parent element (to the root). @ is there if you do not want to access the current object as a whole, and not one of its attributes.

Since I'm not used to the template package, I 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, }) } 
+7
source

All Articles