2014-11-04 02:47 阅读 123

Golang Martini模板在渲染Markdown时仅显示HTML

I am working on writing a simple blog in Golang using Martini, the Martini-Contrib Renderer package, and Blackfriday.

I am able to get the post into the DB and out of the DB with no issues. I even get the Body of the post out of the DB and into my struct as html however when we render the template the output is just plain text html and not looking pretty like it should.

Code is hosted here:


Any help would be great.


You can see what it's doing here:


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dqtl46964 dqtl46964 2014-11-04 05:28

    Golang templates escape variables by default. You can use template.HTML instead of string when it contains HTML and the source is trusted (which, in this instance, it seems to be).


    type HTML string

    HTML encapsulates a known safe HTML document fragment. It should not be used for HTML from a third-party, or HTML with unclosed tags or comments. The outputs of a sound HTML sanitizer and a template escaped by this package are fine for use with HTML.

    The way I would fix it would be by changing this

    type Post struct {
      Title  string
      Body   string
      Author string
      Date   string


    type Post struct {
      Title  string
      Body   template.HTML
      Author string
      Date   string

    And then change

    post.Body = string(blackfriday.MarkdownCommon([]byte(preFormatMarkdown)))


    post.Body = template.HTML(blackfriday.MarkdownCommon([]byte(preFormatMarkdown)))
    点赞 评论 复制链接分享