Golang 使用 blackfriday 将 Markdown 转换为 HTML

更新日期: 2022-06-02 阅读次数: 11677 字数: 351 分类: golang

在用 golang gin 写一个人民币大写转换的工具,网页中的描述信息是在网站后台以 markdown 形式编辑保存的,在前端展示时需要将 markdown 转换为 html。

在网上找了一圈,就发现一个库用的人比较多,那就是 blackfriday。

Golang blackfriday 的项目地址

https://github.com/russross/blackfriday

列表的渲染有问题

用的过程中发现一个问题,列表渲染时,会将下一行的文字,缀到一行。查了半天没找到原因。

突然在文档里找到一个说明:

Hard line breaks. With this extension enabled (it is off by default in the MarkdownBasic and MarkdownCommon convenience functions), newlines in the input translate into line breaks in the output.

对应的配置为

HardLineBreak // Translate newlines into line breaks

如果不启用这个配置,就需要在行尾使用两个空格加换行的方式来表示 markdown 换行。

到了线上又发现一个问题,生产环境本地调试环境运行结果不一致,线上还是排版有问题。后来发现是线上编辑器的换行里包含 "\r"。

类似的一个问题

https://github.com/russross/blackfriday/issues/394

替换掉斜杠 r 就可以了。

实现代码

go get github.com/russross/blackfriday/v2

package controllers

import (
	"bytes"
	"github.com/gin-gonic/gin"
	blackfriday "github.com/russross/blackfriday/v2"
	"html/template"
	"net/http"
	"sunzhongwei.com/go_tool/models"
)

func ChineseMoneyIndex(c *gin.Context) {
	kv, _ := models.GetValue("chinese_money")
	desc_data := []byte(kv.Description)
	desc_data = bytes.Replace(desc_data, []byte("\r"), nil, -1)
	description := string(blackfriday.Run(
		desc_data,
		blackfriday.WithExtensions(blackfriday.CommonExtensions|blackfriday.HardLineBreak),
	))
	c.HTML(http.StatusOK, "chinese_money_index.html", gin.H{
		"kv":          kv,
		"description": template.HTML(description),
	})
}

使用方法参考

https://github.com/russross/blackfriday/issues/394

文档

https://godoc.org/gopkg.in/russross/blackfriday.v2

tags: markdown

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式