在模板中循环遍历对象数组(Go)

huangapple go评论140阅读模式
英文:

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}
			&lt;p&gt;{Title} ({Count})&lt;/p&gt;
		{.end}
	`, nil)
	categories := []Category{
		Category{&quot;Foo&quot;, 3},
		Category{&quot;Bar&quot;, 5},
	}
	tmpl.Execute(os.Stdout, map[string]interface{} {
		&quot;Categories&quot;: categories,
	})
}

huangapple
  • 本文由 发表于 2011年5月29日 13:50:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/6166189.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定