我正在使用 html/template 來提供 html,但我不確定我是否正確使用它。我只粘貼了下面的相關代碼(不完整):這是我的 Go 代碼:func homehandler(w http.ResponseWriter, r *http.Request) { userName := getUserName(r) //this is defined somewhere if userName != "" { t := template.Must(template.New("Tele").Parse(homePage)) t.Execute(w, ReadData()) //ReadData() is a function that reads from the MySQL database and returns a string array } else { (...some code) }}func ReadData() ([]string) { db, _ := sql.Open("mysql", "user1@/my_db") (...some code) rows, err := db.Query("select tweet from posts where username = ?", AddUser.Name) //AddUser is defined somewhere (...some code) for rows.Next() { err := rows.Scan(&tweet) if err != nil { fmt.Println(err) } v := append(tweetarray, tweet) fmt.Println(v) return v } return []string{}}Go 代碼中的 html 部分:const homePage = `<html><h1>hi {{ .userName}}</h1><form action="/home/tweets" method="POST"><label for="name">Tweet</label><input type="text" id="tweet" name="twt"</input><button type="Tweet">Tweet</button><h2>{{range $i := .tweetarray}} {{ $i }} {{end}}</h2>`HTML 根本不出現。我在代碼中做錯了什么?
1 回答

浮云間
TA貢獻1829條經驗 獲得超4個贊
檢查你的錯誤!(對不起,粗體,但這是許多圍棋問題的答案)
t.Execute()
返回錯誤,因為您的模板中有格式錯誤的 html。
html/template:Tele: "<" in attribute name: "</input>\n<button type=\"Tweet\">Tw"
在對此類問題進行故障排除時,請嘗試單獨運行每個部分,或者至少記錄一些調試信息以進行處理。
- 1 回答
- 0 關注
- 359 瀏覽
添加回答
舉報
0/150
提交
取消