Iterating nested structs in golang on a template

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

Iterating nested structs in golang on a template

问题

我有以下代码,并希望在模板中迭代遍历主题,但是我无论如何都无法克服它是一个嵌套容器的事实。

  1. type ThemeList struct {
  2. XMLName xml.Name `xml:"Themes"`
  3. Themes []Theme `xml:"Theme"`
  4. }
  5. type Theme struct {
  6. XMLName xml.Name `xml:"Theme"`
  7. Name string `xml:"Name,attr"`
  8. Page string `xml:"Page,attr"`
  9. Tag string `xml:"Tag,attr"`
  10. Day string `xml:"Day,attr"`
  11. }
  12. // 获取当前的 XML 文档并返回 Themelist[]
  13. func openXML(filename string) ThemeList {
  14. xmlFile, _ := os.Open(filename)
  15. defer xmlFile.Close()
  16. XMLdata, _ := ioutil.ReadAll(xmlFile)
  17. var t ThemeList
  18. xml.Unmarshal(XMLdata, &t)
  19. return t
  20. }

如何在 {{range}} 中输出它们,其中每个主题都是单独的列表项?在模板中,我将使用 .Name.Tag 等来查看它们。

英文:

I have the following code and would like to iterate though the themes in a template, but for the life of me I can't seem to get past the fact it is a nested container.

  1. type ThemeList struct {
  2. XMLName xml.Name `xml:"Themes"`
  3. Themes []Theme `xml:"Theme"`
  4. }
  5. type Theme struct {
  6. XMLName xml.Name `xml:"Theme"`
  7. Name string `xml:"Name,attr"`
  8. Page string `xml:"Page,attr"`
  9. Tag string `xml:"Tag,attr"`
  10. Day string `xml:"Day,attr"`
  11. }
  12. // Fetch the current XML document and return the Themelist[]
  13. func openXML(filename string) ThemeList {
  14. xmlFile, _ := os.Open(filename)
  15. defer xmlFile.Close()
  16. XMLdata, _ := ioutil.ReadAll(xmlFile)
  17. var t ThemeList
  18. xml.Unmarshal(XMLdata, &t)
  19. return t
  20. }

How would one output these in a {{range}} where each theme is part of an individual list items? The output would use .Name .Tag and so on in the template as I look though them.

答案1

得分: 1

使用以下模板:

  1. <ul>{{range .Themes}}
  2. <li>{{.Name}} {{.Tag}}{{end}}
  3. </ul>

并将数据参数作为*ThemeList执行。

Playground示例

英文:

Use the following template:

  1. &lt;ul&gt;{{range .Themes}}
  2. &lt;li&gt;{{.Name}} {{.Tag}}{{end}}
  3. &lt;/ul&gt;

and execute it with the data argument as a *ThemeList.

Playground Example

huangapple
  • 本文由 发表于 2015年9月7日 09:29:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/32429992.html
匿名

发表评论

匿名网友

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

确定