【问题标题】:Inserting HTML to golang template [duplicate]将HTML插入golang模板[重复]
【发布时间】:2017-01-30 07:49:35
【问题描述】:

我在 golang 中有一个模板,其中有一个看起来像这样的字符串:

<some_html> {{ .SomeOtherHTML }} </some_html>

我希望输出是这样的:

<some_html> <the_other_html/> </some_html>

但我看到的是这样的:

<some_html> &lt;the_other_html/&lt; </some_html>

我也在尝试插入一些 JSON,但 golang 正在转义字符并在不应该出现的地方添加 " 之类的内容。

如何在 golang 中插入 HTML 模板而不发生这种情况?

【问题讨论】:

    标签: html json templates go escaping


    【解决方案1】:

    您应该将变量作为template.HTML 传递,而不是作为string

    tpl := template.Must(template.New("main").Parse(`{{define "T"}}{{.Html}}{{.String}}{{end}}`))
    tplVars := map[string]interface{} {
        "Html": template.HTML("<p>Paragraph</p>"),
        "String": "<p>Paragraph</p>",
    }
    tpl.ExecuteTemplate(os.Stdout, "T", tplVars)
    
    //OUTPUT: <p>Paragraph</p>&lt;p&gt;Paragraph&lt;/p&gt;
    

    https://play.golang.org/p/QKKpQJ7gIs

    如您所见,我们作为template.HTML 传递的变量没有被转义,但作为string 传递的变量是。

    【讨论】:

    • 成功了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    相关资源
    最近更新 更多