小编典典

去template.ExecuteTemplate包括html

go

我已按照本教程进行操作:http :
//golang.org/doc/articles/wiki/final.go,并根据我的需要/想要对其进行了略微修改。问题是我想在模板中支持HTML。我意识到这是安全隐患,但目前尚无问题。

页面渲染的结果:

<h1>this<strong>is</strong>a test</h1>

让我解释一下代码:

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'(模板)如下所示:

<h1>{{.Title}}</h1>
<p>[<a href="/edit/{{.Title}}">edit</a>]</p>
<div>{{printf "%s" .Body}}</div>

我尝试过的事情:

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

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

任何指导,不胜感激。如果我感到困惑,请询问,然后我可以修改我的问题。


阅读 326

收藏
2020-07-02

共1个答案

小编典典

将您的[]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
}

然后分配给它。

2020-07-02