英文:
browser not interpreting html template
问题
我在一个非常小的Go应用程序中有一个函数,它对数据库进行查询,检索一些数据并将其插入模板(main.html)中。数据被插入到模板中(参见图片),但是浏览器(Chrome和Firefox)没有解释HTML。我的浏览器其他方面都正常。我在模板方面是否有什么做得不正确的地方?
func Root(w http.ResponseWriter, r *http.Request) {
t := template.Must(template.New("main").ParseFiles("main.html"))
rows, err := db.Query("SELECT title, author, description FROM books")
PanicIf(err)
defer rows.Close()
books := []Book{}
for rows.Next() {
b := Book{}
err := rows.Scan(&b.Title, &b.Author, &b.Description)
PanicIf(err)
books = append(books, b)
}
t.ExecuteTemplate(w, "main.html", books)
}
main.html
<html>
<head>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<table class="table">
<tr>
<th>Title</th>
<th>Author</th>
<th>Description</th>
</tr>
{{ range . }}
<tr>
<td>{{.Title}}</td>
<td>{{.Author}}</td>
<td>{{.Description}}</td>
</tr>
{{ end }}
</table>
</div>
</body>
</html>
图片链接:点击这里
英文:
I have one function in a very small Go application that does a query to a database, retrieves some data and inserts it in the template (main.html). the data is getting inserted into the template (see image), however the html is not being interpreted by the browser (Chrome and Firefox). My browsers are otherwise working fine. Is there something that I'm not doing correct with the template?
func Root(w http.ResponseWriter, r *http.Request) {
t := template.Must(template.New("main").ParseFiles("main.html"))
rows, err := db.Query("SELECT title, author, description FROM books")
PanicIf(err)
defer rows.Close()
books := []Book{}
for rows.Next() {
b := Book{}
err := rows.Scan(&b.Title, &b.Author, &b.Description)
PanicIf(err)
books = append(books, b)
}
t.ExecuteTemplate(w, "main.html", books)
}
main.html
<html>
<head>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<table class="table">
<tr>
<th>Title</th>
<th>Author</th>
<th>Description</th>
</tr>
{{ range . }}
<tr>
<td>{{.Title}}</td>
<td>{{.Author}}</td>
<td>{{.Description}}</td>
</tr>
{{ end }}
</table>
</div>
</body>
</html>
答案1
得分: 2
很可能你正在使用import "text/template"
,而应该使用import "html/template"
,但另一个答案也可以帮你解决这个问题。
英文:
Most likely you are doing import "text/template"
and should be doing import "html/template"
, but the other answer will also fix it for you.
答案2
得分: 1
你需要设置内容类型,尽管它没有自动为你设置,这有点奇怪。
w.Header().Set("Content-Type", "text/html; charset=utf-8")
t.ExecuteTemplate(w, "main.html", books)
//编辑
为了正确起见,你应该在模板的顶部添加 <!DOCTYPE html>
,这与问题无关。
英文:
You need to set the content type, although it's rather weird it didn't automatically set it for you.
w.Header().Set("Content-Type", "text/html; charset=utf-8")
t.ExecuteTemplate(w, "main.html", books)
//edit
Also for correctness sake, you should add <!DOCTYPE html>
to the top of your template, not related to the problem though.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论