我从Go开始,因此这可能是一个简单的答案,但到目前为止我无法在网上找到它。
我有以下结构:
type Answer struct {
AnswerId int
AnswerText string
Selected bool
}
type Answers struct {
answers []Answer
}
type Question struct {
QuestionId int
Answers
QuestionText string
}
这是支持调查问卷的Web应用程序的域模型的简单外观。
func loadPage() (*Question, error) {
return &Question{
QuestionId: 321,
QuestionText: "What's the answer?",
Answers: Answers{
answers: []Answer{
Answer{
AnswerId: 1,
AnswerText: "Answer number 1",
Selected: false,
},
Answer{
AnswerId: 2,
AnswerText: "Answer number 2",
Selected: false,
},
},
},
}, nil
}
在这里你可以看到我已经用一些答案抄问了一个问题。这已经存在,所以我可以向视图发送内容。
func viewHandler(w http.ResponseWriter, r *http.Request) {
p, _ := loadPage()
fmt.Fprintf(w, for _,element := range p.Answers.answers {
//Do something with each element in answers
})
}
这就是我被困的地方;我的viewHandler
。允许我根据answers
切片的内容创建复选框组的语法是什么?我们将非常感激地提供任何帮助。
答案 0 :(得分:1)
首先,您可以采取以下措施来改进代码
Type Answers []Answer
type Question struct {
QuestionId int
// Question is not an "Answers" but has "Answers"
Answers Answers
QuestionText string
}
使用类型为Answers的属性而不是使用嵌入类型来表示“IS-A”关系,应该更合适,并避免复杂的结构定义。
现在这是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