Last active
September 1, 2018 02:25
-
-
Save rtfb/08babeb67d37514f5322722797a6bd6a to your computer and use it in GitHub Desktop.
Demonstrates a simple usage of AST in Blackfriday v2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
bf "gopkg.in/russross/blackfriday.v2" | |
) | |
func main() { | |
md := []byte("Foo\n\n---\n\nBar") | |
html := bf.MarkdownCommon(md) | |
ast := bf.Parse(md, bf.DefaultOptions) | |
var buff bytes.Buffer | |
defaultRenderer := bf.NewHTMLRenderer(bf.HTMLRendererParameters{}) | |
ast.Walk(func(node *bf.Node, entering bool) bf.WalkStatus { | |
if node.Type == bf.HorizontalRule { | |
buff.WriteString(`<div class="separator"></div>`) | |
} else { | |
defaultRenderer.RenderNode(&buff, node, entering) | |
} | |
return bf.GoToNext | |
}) | |
fmt.Printf("md: %q\nhtml: %q\ncustom html: %q\n", md, html, buff.Bytes()) | |
} |
Oh, good catch, I missed it. Thanks!
Fixed.
Is there, perhaps an updated version of this example? I'm trying to use New along with Parse (or Run) to achieve the same thing, but not getting very far.
I sorted it out. Here's an example that works with the current blackfriday.v2 using New and Parse:
package main
import (
"bytes"
"fmt"
bf "gopkg.in/russross/blackfriday.v2"
"io/ioutil"
)
func main() {
input, err := ioutil.ReadFile("sheet.md")
if err != nil {
fmt.Print(err)
}
md := bf.New(bf.WithExtensions(bf.CommonExtensions))
ast := md.Parse(input)
var buff bytes.Buffer
r := bf.NewHTMLRenderer(bf.HTMLRendererParameters{})
ast.Walk(func(node *bf.Node, entering bool) bf.WalkStatus {
if node.Type == bf.Table {
if entering {
buff.WriteString("<div>\n")
r.RenderNode(&buff, node, entering)
} else {
r.RenderNode(&buff, node, entering)
buff.WriteString("</div>\n")
}
} else {
r.RenderNode(&buff, node, entering)
}
return bf.GoToNext
})
fmt.Printf("%s\n", buff.Bytes())
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This looks awesome!
Quick comment. Since this is v2, let's not repeat past mistakes and use idiomatic Go style.
Html
should beHTML
according to https://github.com/golang/go/wiki/CodeReviewComments#initialisms.