英文:
How to pass and access a slice of struct and a struct in template
问题
我有一个结构体类型Topic:
type Topic struct {
Forum_id int
Topic_id int
Author string
Title string
Sub_Title string
Body string
}
还有一个切片类型Replay:
type Replay struct {
Replay_ID int
Topic_ID int
Author string
Body string
}
我需要将这些数据传递到一个模板中,我应该如何使用只有一个变量来传递它?然后在我的模板中如何访问它?
英文:
I have a struct type Topic:
type Topic struct {
Forum_id int
Topic_id int
Author string
Title string
Sub_Title string
Body string
}
And a Slice of type Replay:
type Replay struct {
Replay_ID int
Topic_ID int
Author string
Body string
}
And I need to pass that data into a template, how should I do to pass it with only one variable? And then how should i access it in my template?
答案1
得分: 4
创建一个包装结构体或使用一个映射。例如:
type templateData struct {
Topic Topic
Replays []Replay
}
err := t.Execute(os.Stdout, templateData{topic, replays})
在你的模板中,你可以通过它们的字段名来访问它们。
{{ .Topic.Title }}
{{ range .Replays }}
{{ .Body }}
{{ end }}
英文:
Create a wrapper struct or use a map. For example
type templateData struct {
Topic Topic
Replays []Replay
}
err := t.Execute(os.Stdout, templateData{topic, replays})
In your template, you can access both with their field name.
{{ .Topic.Title }}
{{ range .Replays }}
{{ .Body }}
{{ end }}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论