英文:
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
执行。
英文:
Use the following template:
<ul>{{range .Themes}}
<li>{{.Name}} {{.Tag}}{{end}}
</ul>
and execute it with the data argument as a *ThemeList
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论