markdown/markdown.go (view raw)
1package markdown
2
3import (
4 "os"
5 "path/filepath"
6 "text/template"
7 "time"
8
9 bfc "github.com/Depado/bfchroma"
10 bf "github.com/russross/blackfriday/v2"
11)
12
13var bfFlags = bf.UseXHTML | bf.Smartypants | bf.SmartypantsFractions |
14 bf.SmartypantsDashes | bf.NofollowLinks
15var bfExts = bf.NoIntraEmphasis | bf.Tables | bf.FencedCode | bf.Autolink |
16 bf.Strikethrough | bf.SpaceHeadings | bf.BackslashLineBreak |
17 bf.HeadingIDs | bf.Footnotes | bf.NoEmptyLineBeforeBlock
18
19type Output struct {
20 HTML []byte
21 Meta Matter
22}
23
24// Renders markdown to html, and fetches metadata.
25func (out *Output) RenderMarkdown(source []byte) {
26 md := MarkdownDoc{}
27 md.Extract(source)
28
29 out.HTML = bf.Run(
30 md.Body,
31 bf.WithRenderer(
32 bfc.NewRenderer(
33 bfc.ChromaStyle(Icy),
34 bfc.Extend(
35 bf.NewHTMLRenderer(bf.HTMLRendererParameters{
36 Flags: bfFlags,
37 }),
38 ),
39 ),
40 ),
41 bf.WithExtensions(bfExts),
42 )
43 out.Meta = md.Frontmatter
44}
45
46// Renders out.HTML into dst html file, using the template specified
47// in the frontmatter. data is the template struct.
48func (out *Output) RenderHTML(dst, tmplDir string, data interface{}) error {
49 metaTemplate := out.Meta["template"]
50 if metaTemplate == "" {
51 metaTemplate = "text.html"
52 }
53
54 t, err := template.New("").Funcs(template.FuncMap{
55 "parsedate": func(s string) time.Time {
56 date, _ := time.Parse("2006-01-02", s)
57 return date
58 },
59 }).ParseGlob(filepath.Join(tmplDir, "*.html"))
60 if err != nil {
61 return err
62 }
63
64 w, err := os.Create(dst)
65 if err != nil {
66 return err
67 }
68
69 if err = t.ExecuteTemplate(w, metaTemplate, data); err != nil {
70 return err
71 }
72 return nil
73}