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

作者:lu569368 时间:2023-06-20 07:37:32 

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 }}

来源:https://studygolang.com/articles/26395

标签:go,markdown
0
投稿

猜你喜欢

  • 悟透JavaScript

    2008-05-29 22:15:00
  • 有故事的网页设计——Flash网站奇妙之旅

    2011-01-20 19:58:00
  • 网页设计十大诀窍

    2007-10-19 13:03:00
  • 13个你希望早点知道的实用WordPress SQL查询语句[译]

    2010-02-28 12:48:00
  • sql server 触发器实例代码

    2012-01-05 19:09:28
  • Refactoring HTML 书评

    2008-07-10 12:00:00
  • 如何利用数据库内容建立一个下拉式列表?

    2010-01-01 15:46:00
  • Mootools常用方法扩展(三)

    2009-01-14 20:07:00
  • asp如何终止浏览器的 CAHCE 页面?

    2010-07-07 12:25:00
  • 如何判断JavaScript变量的类型

    2009-02-25 12:28:00
  • 用SQL语句完成SQL Server数据库的修复

    2008-11-24 20:49:00
  • FrontPage 2002应用技巧四则

    2008-08-17 10:57:00
  • 如何把中文转换为UNICODE?

    2009-11-07 18:39:00
  • innerHTML,outerHTML,innerText,outerText用法

    2008-02-15 12:22:00
  • 用XML创建可排序、分页的数据显示页面

    2008-04-22 18:25:00
  • 建立用户体验过程的实用指南

    2007-11-19 12:53:00
  • ASPImage组件的实现过程[图]

    2008-02-03 15:37:00
  • 使用游标进行PHP SQLSRV查询的方法与注意事项

    2023-05-22 10:51:10
  • 使用 JavaScript 获取本地盘符

    2010-01-12 13:49:00
  • javascript面向对象技术基础(二)

    2010-02-07 13:09:00
  • asp之家 网络编程 m.aspxhome.com