英文:
GO: error serving templates with html/template
问题
我正在使用html/template来提供HTML服务,但我不确定我是否使用正确。我只粘贴了相关的代码(不完整):
这是我的Go代码:
func homehandler(w http.ResponseWriter, r *http.Request) {
userName := getUserName(r) //这是在某个地方定义的
if userName != "" {
t := template.Must(template.New("Tele").Parse(homePage))
t.Execute(w, ReadData()) //ReadData()是一个从MySQL数据库读取并返回字符串数组的函数
} else {
(...一些代码)
}
}
func ReadData() ([]string) {
db, _ := sql.Open("mysql", "user1@/my_db")
(...一些代码)
rows, err := db.Query("select tweet from posts where username = ?", AddUser.Name) //AddUser在某个地方定义
(...一些代码)
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根本没有显示出来。我在代码中做错了什么?
英文:
I'm using html/template to serve html but I'm not sure if I'm using it correctly. I've only pasted the relevant code below (not complete):
This is my Go code:
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{}
}
The html portion in the Go code:
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>
`
The HTML doesn't appear at all. What am I doing wrong in the code?
答案1
得分: 3
检查你的错误!(对不起,这是对很多Go问题的答案)
t.Execute()
返回一个错误,因为你的模板中有格式错误的HTML。
在解决这类问题时,尝试将每个部分单独运行,或至少记录一些调试信息以供参考。
英文:
Check your errors! (sorry for the bold, but this is the answer to so many Go questions)
t.Execute()
returns an error because you have malformed html in your template.
html/template:Tele: "<" in attribute name: "</input>\n<button type=\"Tweet\">Tw"
When troubleshooting something like this, try running each of the parts in isolation, or at least log some debugging information to go with it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论