1 回答
TA贡献1802条经验 获得超4个赞
首先,您可以通过以下方式改进代码
Type Answers []Answer
type Question struct {
QuestionId int
// Question is not an "Answers" but has "Answers"
Answers Answers
QuestionText string
}
与其使用嵌入类型来表示“IS-A”关系,不如使用 Answers 类型的属性更合适,并避免复杂的结构定义。
现在这就是你的viewHandler样子:
func ViewHandler(w http.ResponseWriter, r *http.Request) {
// This should be loaded from another template file
const tpl = `
<!DOCTYPE html>
<html>
<body>
<form action="demo" method="POST">
<!-- Once the pagedata struct exists in the context,
we can query its field value with dot notation -->
<h3>{{.QuestionText}}</h3>
{{range .Answers}}
<input type="radio" name="" {{if .Selected}}checked{{end}}
>{{.AnswerText}}<br>
{{end}}
</section>
</body>
</html>
`
t, _ := template.New("questionaire").Parse(tpl)
pagedata, _ := loadPage()
// Pass in the data struct
_ = t.Execute(w, pagedata)
}
您只需要解析模板,然后通过Execute传递数据结构,您希望其数据在响应的上下文中可用。
在此处查看完整代码https://play.golang.org/p/6PbX6YsLNt
- 1 回答
- 0 关注
- 147 浏览
添加回答
举报