Donald Plummer's Blog

home

Markdown in Go templates

19 Mar 2014

While building a blog in Go, I ran into a problem. I was storing the blog posts in markdown format. Using the blackfriday markdown processor, I was getting back raw HTML:

func (article *Article) ParsedBody() string {
  output := blackfriday.MarkdownCommon([]byte(article.Body))
  return string(output)
}

Then in my template I'd try to render the ParsedBody:

  <div class="blog-post">
    <!-- title, etc ... -->

  </div>

But that escapes the body:

  <div class="blog-post">
    <!-- title, etc ... -->
    &gt;p&lt;Hello world!&gt;/p&lt;
  </div>

The answer is to not return a string, but to return a template.HTML type:

func (article *Article) ParsedBody() template.HTML {
  output := blackfriday.MarkdownCommon([]byte(article.Body))
  return template.HTML(output)
}