all repos — vite @ c9a8e448d78283a7faf80fd20cb0eed900914153

a fast (this time, actually) and minimal static site generator

markdown/markdown.go (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
package markdown

import (
	"os"
	"path/filepath"
	"text/template"

	bfc "github.com/Depado/bfchroma"
	bf "github.com/russross/blackfriday/v2"
)

var bfFlags = bf.UseXHTML | bf.Smartypants | bf.SmartypantsFractions |
	bf.SmartypantsDashes | bf.NofollowLinks
var bfExts = bf.NoIntraEmphasis | bf.Tables | bf.FencedCode | bf.Autolink |
	bf.Strikethrough | bf.SpaceHeadings | bf.BackslashLineBreak |
	bf.HeadingIDs | bf.Footnotes | bf.NoEmptyLineBeforeBlock

type Output struct {
	HTML []byte
	Meta Matter
}

// Renders markdown to html, and fetches metadata.
func (out *Output) RenderMarkdown(source []byte) {
	md := MarkdownDoc{}
	md.Extract(source)

	out.HTML = bf.Run(
		md.Body,
		bf.WithRenderer(
			bfc.NewRenderer(
				bfc.ChromaStyle(Icy),
				bfc.Extend(
					bf.NewHTMLRenderer(bf.HTMLRendererParameters{
						Flags: bfFlags,
					}),
				),
			),
		),
		bf.WithExtensions(bfExts),
	)
	out.Meta = md.Frontmatter
}

// Renders out.HTML into dst html file, using the template specified
// in the frontmatter. data is the template struct.
func (out *Output) RenderHTML(dst, tmplDir string, data interface{}) error {
	metaTemplate := out.Meta["template"].(string)
	if metaTemplate == "" {
		metaTemplate = "text.html"
	}

	t, err := template.ParseGlob(filepath.Join(tmplDir, "*.html"))
	if err != nil {
		return err
	}

	w, err := os.Create(dst)
	if err != nil {
		return err
	}

	if err = t.ExecuteTemplate(w, metaTemplate, data); err != nil {
		return err
	}
	return nil
}