简体   繁体   中英

Iterating nested structs in golang on a template

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.

Use the following template:

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

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

Playground Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM