我有一个结构类型主题:
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 }
我需要将该数据传递到模板中,我应该如何做才能仅使用一个变量传递它?那么我应该如何在我的模板中访问它?
创建包装器结构或使用映射。例如
type templatedata struct { topic topic replays []replay } err := t.execute(os.stdout, templatedata{topic, replays})
在您的模板中,您可以使用字段名称来访问两者。
{{ .Topic.Title }} {{ range .Replays }} {{ .Body }} {{ end }}