首页 > 文章列表 > Go template.ExecuteTemplate 包含 html

Go template.ExecuteTemplate 包含 html

golang
452 2023-03-08

问题内容

我遵循了本教程: http: //golang.org/doc/articles/wiki/final.go并根据我的需要/想要稍微修改了它。问题是我想在模板中支持 HTML。我意识到这是一个安全风险,但目前还不是问题。

页面渲染的结果:

thisisa test

让我解释一下代码:

type Page struct {
    Title string
    Body  []byte
}

我想要 HTML 的数据存储在Page.Body. 这是类型[]byte,这意味着我不能(或者我可以?)运行html/template.HTML(Page.Body)该函数需要一个字符串。

我有这个预渲染模板:

var (
    templates = template.Must(template.ParseFiles("tmpl/edit.html", "tmpl/view.html"))
)

实际ExecuteTemplate看起来像这样:

err := templates.ExecuteTemplate(w, tmpl+".html", p)

其中 w 是w http.ResponseWriter, tmpl 是tmpl string, p 是p *Page

最后我的'view.html'(模板)如下所示:

{{.Title}}

[edit]

{{printf "%s" .Body}}

我尝试过的事情:

  • {{printf "%s" .Body | html}}什么都不做
  • 我已经包含github.com/russross/blackfriday(Markdown 处理器)并运行p.Body = blackfriday.MarkdownCommon(p.Body)了正确地将 Markdown 转换为 HTML,但 HTML 仍然作为实体输出。
  • 编辑: 我尝试了以下代码(我不知道为什么格式混乱),它仍然输出完全相同。

var s template.HTML s = template.HTML(p.Body) p.Body = []byte(s)

非常感谢任何指导。如果我感到困惑,请询问,我可以修改我的问题。

正确答案

将您的[]byte或转换string为类型template.HTML在此处记录)

p.Body = template.HTML(s) // where s is a string or []byte

然后,在您的模板中,只需:

{{.Body}}

它将被打印而不会转义。

编辑

为了能够在页面正文中包含 HTML,您需要更改Page类型声明:

type Page struct {
    Title string
    Body  template.HTML
}

然后分配给它。