Skip to content

Instantly share code, notes, and snippets.

@rtfb
Last active September 1, 2018 02:25
Show Gist options
  • Save rtfb/08babeb67d37514f5322722797a6bd6a to your computer and use it in GitHub Desktop.
Save rtfb/08babeb67d37514f5322722797a6bd6a to your computer and use it in GitHub Desktop.
Demonstrates a simple usage of AST in Blackfriday v2
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())
}
@swelljoe
Copy link

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.

@swelljoe
Copy link

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