Iterating nested structs in golang on a template

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

Iterating nested structs in golang on a template

问题

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

type ThemeList struct {
    XMLName xml.Name `xml:"Themes"`
    Themes  []Theme  `xml:"Theme"`
}

type Theme struct {
    XMLName xml.Name `xml:"Theme"`
    Name    string   `xml:"Name,attr"`
    Page    string   `xml:"Page,attr"`
    Tag     string   `xml:"Tag,attr"`
    Day     string   `xml:"Day,attr"`
}

// 获取当前的 XML 文档并返回 Themelist[]
func openXML(filename string) ThemeList {
    xmlFile, _ := os.Open(filename)
    defer xmlFile.Close()
    XMLdata, _ := ioutil.ReadAll(xmlFile)

    var t ThemeList
    xml.Unmarshal(XMLdata, &t)

    return t
}

如何在 {{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.

type ThemeList struct {
    XMLName xml.Name `xml:"Themes"`
    Themes []Theme `xml:"Theme"`
}

type Theme struct {
    XMLName xml.Name `xml:"Theme"`
    Name string `xml:"Name,attr"`
    Page string `xml:"Page,attr"`
    Tag string `xml:"Tag,attr"`
    Day string `xml:"Day,attr"`
}

// Fetch the current XML document and return the Themelist[]
func openXML(filename string) ThemeList {

    xmlFile, _ := os.Open(filename)
    defer xmlFile.Close()
    XMLdata, _ := ioutil.ReadAll(xmlFile)

    var t ThemeList
    xml.Unmarshal(XMLdata, &t)

    return t
}

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

使用以下模板:

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

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

Playground示例

英文:

Use the following template:

&lt;ul&gt;{{range .Themes}}
  &lt;li&gt;{{.Name}} {{.Tag}}{{end}}
&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:

确定