Golang中HTML模板返回文本而非HTML的问题如何解决
Golang中HTML模板返回文本而非HTML的问题如何解决 我有以下代码:
package main
import (
"fmt"
htmlTempl "html/template"
"log"
"net/http"
)
var templatesHtml *htmlTempl.Template
var err error
func init() {
fmt.Println("Starting up.")
templatesHtml = htmlTempl.Must(htmlTempl.ParseGlob("templates/*.html"))
}
func test(w http.ResponseWriter, r *http.Request) {
err = templatesHtml.ExecuteTemplate(w, "other.html", nil)
if err != nil {
log.Fatalln(err)
}
}
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./public"))))
http.HandleFunc("/test", test)
server.ListenAndServe()
}
我的模板是:
// Content of base.html:
{{define "base"}}
<html>
<head>{{template "head" .}}</head>
<body>{{template "body" .}}</body>
</html>
{{end}}
以及
// Content of other.html:
{{template "base" .}}
{{define "head"}}<title>other</title>{{end}}
{{define "body"}}other{{end}}
我在 http://127.0.0.1:8080/test 得到的输出是:

而我期望显示的是正常的HTML页面!
更多关于Golang中HTML模板返回文本而非HTML的问题如何解决的实战教程也可以访问 https://www.itying.com/category-94-b0.html
2 回复
我找到了问题所在,错误在于使用了 // 作为注释标记。通过将它们替换为 HTML 内容注释标记来解决,如下所示:
<!-- Content of other.html: -->
{{template "base" .}}
{{define "head"}}<title>other</title>{{end}}
{{define "body"}}other{{end}}
现在它工作正常了。
更多关于Golang中HTML模板返回文本而非HTML的问题如何解决的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
问题在于模板定义和执行方式不匹配。ExecuteTemplate 期望的是已定义的模板名称,但您传递的是文件名。以下是修正后的代码:
package main
import (
"fmt"
htmlTempl "html/template"
"log"
"net/http"
)
var templatesHtml *htmlTempl.Template
var err error
func init() {
fmt.Println("Starting up.")
// 解析所有模板文件
templatesHtml = htmlTempl.Must(htmlTempl.ParseGlob("templates/*.html"))
}
func test(w http.ResponseWriter, r *http.Request) {
// 执行名为 "other" 的模板,而不是文件名 "other.html"
err = templatesHtml.ExecuteTemplate(w, "other", nil)
if err != nil {
log.Fatalln(err)
}
}
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./public"))))
http.HandleFunc("/test", test)
server.ListenAndServe()
}
模板文件保持不变,但注意 other.html 中定义的是名为 “other” 的模板:
<!-- templates/other.html -->
{{define "other"}}
{{template "base" .}}
{{define "head"}}<title>other</title>{{end}}
{{define "body"}}other{{end}}
{{end}}
关键点是:
ExecuteTemplate的第二个参数应该是模板定义中的名称({{define "name"}}),而不是文件名- 确保模板文件中正确定义了模板名称
- 所有模板文件都会被
ParseGlob解析,模板名称在全局命名空间中
如果仍然显示文本而非HTML,检查响应头是否正确设置了Content-Type。可以添加中间件确保:
func test(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
err = templatesHtml.ExecuteTemplate(w, "other", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}

