从切片创建复选框组

我从 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切片内容创建复选框组的语法是什么?任何帮助将不胜感激。


holdtom
浏览 148回答 1
1回答

慕虎7371278

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

相关分类

Go