当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > go语言实现markdown解析库的方法示例

go语言实现markdown解析库的方法示例

2020年05月13日  | 移动技术网IT编程  | 我要评论

色姊姊真舒服,湖北新闻联播,红米手机的缺点

blackfriday是在go中实现的markdown处理器。您可以安全地输入用户提供的数据,速度快,支持通用扩展(表,智能标点符号替换等),并且对于所有utf-8(unicode)都是安全的输入。

当前支持html输出以及smartypants扩展。

使用

首先当然要引入:

import github.com/russross/blackfriday

然后

output := blackfriday.markdownbasic(input)

这里input是[]byte类型,可以将markdown类型的字符串强转为[]byte,即input = []byte(string)

如果想过滤不信任的内容,使用以下方法:

代码:

package main

import (
  "fmt"

  "github.com/microcosm-cc/bluemonday"
  "github.com/russross/blackfriday"
)

func main() {
  input := []byte("### 5lmh.com是个不错的go文档网站")
  unsafe := blackfriday.markdowncommon(input)
  html := bluemonday.ugcpolicy().sanitizebytes(unsafe)
  fmt.println(string(html))
}

基本上就这些操作

我的使用方法是在添加新文章时,将表单提交的数据直接通过上面的方法转换后,将markdown和转换后的内容都存储到数据库中

不过我在前端渲染时,又出现了问题,就是转换后的内容中的html标签会直接显示在网页上,为避免这种状况,我使用了自定义模板函数

  // 定义模板函数
  func unescaped(x string) interface{} { return template.html(x)}

  // 注册模板函数
  t := template.new("post.html")
  t = t.funcs(template.funcmap{"unescaped": unescaped})
  t, _ = t.parsefiles("templates/post.html")
  t.execute(w, post)

  // 使用模板函数

  {{ .content|unescaped }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网