dongxinpa3101 2014-04-21 13:47
浏览 157
已采纳

如何在Go中使用Blackfriday将markdown呈现为html?

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?

  • 写回答

1条回答 默认 最新

  • dongtaihui5131 2014-04-21 19:16
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真