增加markdown支持。
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
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())
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRenderMarkdown(t *testing.T) {
|
||||
// Markdown 语法渲染
|
||||
out := string(RenderMarkdown("# 标题\n\n**加粗** 和 `代码`"))
|
||||
if !strings.Contains(out, "<h1>标题</h1>") || !strings.Contains(out, "<strong>加粗</strong>") || !strings.Contains(out, "<code>代码</code>") {
|
||||
t.Errorf("Markdown 渲染结果不符合预期: %s", out)
|
||||
}
|
||||
|
||||
// GFM 表格
|
||||
out = string(RenderMarkdown("| a | b |\n| --- | --- |\n| 1 | 2 |"))
|
||||
if !strings.Contains(out, "<table>") {
|
||||
t.Errorf("GFM 表格未渲染: %s", out)
|
||||
}
|
||||
|
||||
// 兼容旧文章的 HTML 内容
|
||||
out = string(RenderMarkdown("<div class=\"old\"><p>旧的HTML内容</p></div>"))
|
||||
if !strings.Contains(out, "<div class=\"old\">") {
|
||||
t.Errorf("HTML 内容未透传: %s", out)
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ func templateFuncs() template.FuncMap {
|
||||
"html": func(s string) template.HTML {
|
||||
return template.HTML(s)
|
||||
},
|
||||
"markdown": RenderMarkdown,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user