html - Golang 模板将 html 解释为纯文本
问题描述
我有一个 Golang 模板,将我的 html 解释为纯文本。
我已w.Header().Set("Content-Type", "text/html; charset=utf-8")
在传递给的函数中包含该行,http.HandleFunc()
但是我的 html 被解释为纯文本。
package main
import (
"html/template"
"io"
"net/http"
)
func main() {
http.HandleFunc("/dog", dog)
http.Handle("/resources/", http.StripPrefix("/resources", http.FileServer(http.Dir("./assets"))))
http.ListenAndServe(":8080", nil)
}
var tpl *template.Template
func init() {
tpl = template.Must(template.ParseFiles("index.gohtml"))
}
func dog(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
data := []string{`<h1>This is from dog</h1>`, `<img src="/assets/img/dog.jpg">`}
tpl.ExecuteTemplate(w, "index.gohtml", data)
}
这是我的index.gohtml
模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
{{range .}}
{{.}}
{{end}}
</body>
</html>
解决方案
正如评论中所指出的,答案是在作为数据传递到模板时[]string{}
替换为。[]template.HTML{}
推荐阅读
- python - 如何克服 PySimpleGUI 中的“NoneTypeObject”错误?
- java - 如何从 char 数组生成组合?
- r - R shiny 中的下载处理程序不会生成 PDF 文件(使用 rmarkdown::render())
- javascript - 无法在 useEffect() 中从 AXIOS 获取数据
- julia - 使用预编译包发布 Julia 的最简单方法
- c# - 使用反射查找 Type() 的所有类,对它们进行排序并调用命名方法
- docker - docker容器内的crontab问题
- javascript - 使用 OpenCV.js 将图像放在另一个图像上
- django - 我需要 m2m .csv 导出中两个模型的多个字段
- python - 如何调试 CDK python 应用程序并获得可用的上下文变量?