Go template.ExecuteTemplate include html

后端 未结 8 1951
我在风中等你
我在风中等你 2020-12-01 10:19

I have followed this tutorial: http://golang.org/doc/articles/wiki/final.go and have slightly modified it for my needs/wants. The problem is I would like to support HTML in

8条回答
  •  时光取名叫无心
    2020-12-01 11:11

    Take a look at the template.HTML type. It can be used to encapsulate a known safe fragment of HTML (like the output from Markdown). The "html/template" package will not escape this this type.

    type Page struct {
        Title string
        Body template.HTML
    }
    
    page := &Page{
        Title: "Example",
        Body:  template.HTML(blackfriday.MarkdownCommon([]byte("foo bar")),
    }
    

    I usually write my own func Markdown(text string) html.Template method that calls blackfriday with the appropriate config and does some type conversions. Another alternative might be also to register a "html" func in the template parser, that allows you to output any value without any escaping by doing something like {{html .MySafeStr}}. The code might look like:

    var tmpl = template.Must(template.New("").Funcs(template.FuncMap{
        "html": func(value interface{}) template.HTML {
            return template.HTML(fmt.Sprint(value))
        },
    }).ParseFiles("file1.html", "file2.html"))
    

提交回复
热议问题