Blackfriday是在Go中實(shí)現(xiàn)的Markdown處理器。您可以安全地輸入用戶提供的數(shù)據(jù),速度快,支持通用擴(kuò)展(表,智能標(biāo)點(diǎn)符號(hào)替換等),并且對(duì)于所有utf-8(unicode)都是安全的輸入。
當(dāng)前支持HTML輸出以及Smartypants擴(kuò)展。
使用
首先當(dāng)然要引入:
import github.com/russross/blackfriday
然后
output := blackfriday.MarkdownBasic(input)
這里input是[]byte類型,可以將markdown類型的字符串強(qiáng)轉(zhuǎn)為[]byte,即input = []byte(string)
如果想過濾不信任的內(nèi)容,使用以下方法:
代碼:
package main
import (
"fmt"
"github.com/microcosm-cc/bluemonday"
"github.com/russross/blackfriday"
)
func main() {
input := []byte("### 5lmh.com是個(gè)不錯(cuò)的go文檔網(wǎng)站")
unsafe := blackfriday.MarkdownCommon(input)
html := bluemonday.UGCPolicy().SanitizeBytes(unsafe)
fmt.Println(string(html))
}
基本上就這些操作
我的使用方法是在添加新文章時(shí),將表單提交的數(shù)據(jù)直接通過上面的方法轉(zhuǎn)換后,將markdown和轉(zhuǎn)換后的內(nèi)容都存儲(chǔ)到數(shù)據(jù)庫(kù)中
不過我在前端渲染時(shí),又出現(xiàn)了問題,就是轉(zhuǎn)換后的內(nèi)容中的html標(biāo)簽會(huì)直接顯示在網(wǎng)頁(yè)上,為避免這種狀況,我使用了自定義模板函數(shù)
// 定義模板函數(shù)
func unescaped(x string) interface{} { return template.HTML(x)}
// 注冊(cè)模板函數(shù)
t := template.New("post.html")
t = t.Funcs(template.FuncMap{"unescaped": unescaped})
t, _ = t.ParseFiles("templates/post.html")
t.Execute(w, post)
// 使用模板函數(shù)
{{ .Content|unescaped }}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- 漂亮的Django Markdown富文本app插件的實(shí)現(xiàn)
- Django渲染Markdown文章目錄的方法示例