32 lines
878 B
Go
32 lines
878 B
Go
package utils
|
|
|
|
import (
|
|
"bytes"
|
|
"html/template"
|
|
|
|
"github.com/yuin/goldmark"
|
|
"github.com/yuin/goldmark/extension"
|
|
goldmarkhtml "github.com/yuin/goldmark/renderer/html"
|
|
)
|
|
|
|
// markdownEngine 全局 Markdown 渲染引擎
|
|
// 启用 GFM 扩展(表格、删除线、任务列表、自动链接等)
|
|
// 启用 WithUnsafe 允许原始 HTML 透传,兼容旧文章中的 HTML 内容
|
|
var markdownEngine = goldmark.New(
|
|
goldmark.WithExtensions(extension.GFM),
|
|
goldmark.WithRendererOptions(
|
|
goldmarkhtml.WithUnsafe(),
|
|
goldmarkhtml.WithHardWraps(),
|
|
),
|
|
)
|
|
|
|
// RenderMarkdown 将 Markdown 文本渲染为 HTML
|
|
func RenderMarkdown(source string) template.HTML {
|
|
var buf bytes.Buffer
|
|
if err := markdownEngine.Convert([]byte(source), &buf); err != nil {
|
|
// 渲染失败时原样返回,避免页面空白
|
|
return template.HTML(source)
|
|
}
|
|
return template.HTML(buf.String())
|
|
}
|