在 golang html 模板中将“转义为”

escaping ' to ' in golang html template

如何防止在 html 模板中将 ' 转义为 '

package main

import (
    "html/template"
    "os"
)

const tmpl = `<html>
    <head>
        <title>{{.Title}}</title>
    </head>
</html>`

func main() {
    t := template.Must(template.New("ex").Parse(tmpl))
    v := map[string]interface{}{
        "Title": template.HTML("Hello World'"),
    }
    t.Execute(os.Stdout, v)
}

它输出:

<html>
    <head>
        <title>Hello World'</title>
    </head>
</html>

期望的输出:

<html>
    <head>
        <title>Hello World'</title>
    </head>
</html>

playouground

@dyoo 已经解释清楚 <title> 内容被视为 RCDATA。进行转义的代码是 here。分支 if t == contentTypeHTMLtemplate.HTML.

发生的情况

如果您确实需要控制源的输出,请使用text/template并手动进行转义。