首页 > 解决方案 > 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>

标签: htmlgo

解决方案


正如评论中所指出的,答案是在作为数据传递到模板时[]string{}替换为。[]template.HTML{}


推荐阅读