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

如何在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 stm32f407使用DMA问题
  • ¥15 您好 这个API接口该怎么弄 网站搭建好了 API也有 现在就不知道该怎么填写API 不知道怎么用
  • ¥88 用uniapp写一个多端的程序,用到高德地图,用高德的JSAPI吗?
  • ¥20 关于#c++#的问题:水果店管理系统
  • ¥30 dbLinq最新版linq sqlite
  • ¥20 对D盘进行分盘之前没有将visual studio2022卸载掉,现在该如何下载回来
  • ¥15 完成虚拟机环境配置,还有安装kettle
  • ¥15 2024年全国大学生数据分析大赛A题:直播带货与电商产品的大数据分析 问题5. 请设计一份优惠券的投放策略,需要考虑优惠券的数量、优惠券的金额、投放时间段和投放商品种类等因素。求具体的python代码
  • ¥15 有人会搭建生鲜配送自营+平台的管理系统吗
  • ¥15 用matlab写代码