2015-11-15 41 views
0

我剛開始使用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

使用Go的[HTML /模板(https://golang.org/pkg/html/template/)包:不轉義文本打印到響應。您可以在模板中調用'range'來填充HTML複選框,其中當前的'.AnswerID'爲名稱,'.AnswerText'爲標籤,'.Selected'爲值。 – elithrar

回答

1

首先,這裏是你能做些什麼來提高代碼

Type Answers []Answer 

type Question struct { 
    QuestionId int 
    // Question is not an "Answers" but has "Answers" 
    Answers Answers 
    QuestionText string 
} 

而不是使用嵌入式類型來表示「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

+0

不錯。沒有回答我的問題,但通過代碼肯定有所改進。謝謝! :) – Stu1986C

+0

@ Stu1986C認爲我無法在評論中輸入代碼。將重新檢查問題是否未得到解答。 – PieOhPah

+0

@ Stu1986C答案已被編輯和添加。 – PieOhPah