英文:
Looping over an array of objects in a template (Go)
问题
我正在将一个结构体(其中一个元素是Category对象的数组)传递给模板进行渲染。在模板中,我有类似以下代码的内容:
{.repeated section Categories}
<p>{@}</p>
{.end}
然而,每个Category都有一些自己的元素,我需要能够访问(例如Title)。我尝试过{@.Title}之类的方法,但似乎找不到正确的语法来实现这一点。在模板中的循环中如何访问数组中数据的成员?
英文:
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?
答案1
得分: 7
你只需要写{Title}
。
每当模板包遇到一个标识符时,它会尝试在当前对象中查找,如果找不到,则尝试在父对象中查找(直到根对象)。@
只是用来访问整个当前对象,而不是它的属性之一。
由于我也不熟悉模板包,我创建了一个小例子:
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,
})
}
英文:
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,
})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论