質問

I have a struct like this:

type Page struct {
    Content  string
}

then I read a markdown file and assign to a variable:

data, err := ioutil.ReadFile("a.md")
lines = string(data)
page.Content = markdownRender([]byte(lines))

The markdown file is like this:

##Hello World

###Holo Go

and then I put it into markdown render function and return a string value:

func markdownRender(content []byte) string {
  htmlFlags := 0
  htmlFlags |= blackfriday.HTML_USE_SMARTYPANTS
  htmlFlags |= blackfriday.HTML_SMARTYPANTS_FRACTIONS

  renderer := blackfriday.HtmlRenderer(htmlFlags, "", "")

  extensions := 0
  extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
  extensions |= blackfriday.EXTENSION_TABLES
  extensions |= blackfriday.EXTENSION_FENCED_CODE
  extensions |= blackfriday.EXTENSION_AUTOLINK
  extensions |= blackfriday.EXTENSION_STRIKETHROUGH
  extensions |= blackfriday.EXTENSION_SPACE_HEADERS

  return string(blackfriday.Markdown(content, renderer, extensions))
}

and finally I call the page.Content in a html template and generate a static html:

{{.Content}}

but in the generated html it shows in the browser (I tried it in the chrome and safari) is like this (not the source code, it just shows in the page):

<p>##Hello World ###Holo Go </p>

but I want it like this

Hello World

Holo Go

So, how can I do this?

役に立ちましたか?

解決

First, your markdown input is not quite right -- headings should have whitespace separating the #s from the text. You can verify this using blackfriday-tool:

$ echo ##Hello | blackfriday-tool
<p>##Hello</p>

$ echo ## Hello | blackfriday-tool
<h2>Hello</h2>

Second, if you feed the HTML output from blackfriday into a html/template, it is going to be automatically escaped for safety.

If you trust the markdown input and blackfriday's HTML output, then you can tell the template system to trust the content by wrapping it in a html/template HTML value:

type Page struct {
    Content template.HTML
}

err = t.ExecuteTemplate(w, "page", Page{Content: template.HTML(s)})

See http://play.golang.org/p/eO7KDJMlb8 for an example.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top