Created
March 19, 2022 12:56
-
-
Save jfjensen/3d8d4e6abb59fe6ca4415102ca932403 to your computer and use it in GitHub Desktop.
This is the golang code for rendering a markdown file to HTML/Bulma CSS
This file contains hidden or 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" | |
"github.com/gomarkdown/markdown" | |
"github.com/gomarkdown/markdown/ast" | |
"github.com/gomarkdown/markdown/html" | |
"io" | |
"io/ioutil" | |
"strconv" | |
"text/template" | |
) | |
func main() { | |
htmlHeader := ` | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css"> | |
<title>Blog Post Example</title> | |
</head> | |
<body> | |
<br> | |
<div class="container is-max-desktop"> | |
<div class="content">` | |
htmlFooter := ` | |
</div> | |
</div> | |
<br> | |
</body> | |
</html>` | |
md, err := ioutil.ReadFile("./blog-post-example.md") | |
if err != nil { | |
panic(err) | |
} | |
opts := html.RendererOptions{ | |
Flags: html.FlagsNone, | |
RenderNodeHook: renderHook, | |
} | |
renderer := html.NewRenderer(opts) | |
output := string(markdown.ToHTML(md, nil, renderer)) | |
t := template.New("Render") | |
t, err = t.Parse(htmlHeader + "{{.}}" + htmlFooter) | |
t = template.Must(t, err) | |
var processed bytes.Buffer | |
t.Execute(&processed, output) | |
err = ioutil.WriteFile("index.html", processed.Bytes(), 0644) | |
if err != nil { | |
panic(err) | |
} | |
} | |
func renderHook(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) { | |
if _, ok := node.(*ast.Heading); ok { | |
level := strconv.Itoa(node.(*ast.Heading).Level) | |
if entering && level == "1" { | |
w.Write([]byte(`<h1 class="title is-1 has-text-centered">`)) | |
} else if entering { | |
w.Write([]byte("<h" + level + ">")) | |
} else { | |
w.Write([]byte("</h" + level + ">")) | |
} | |
return ast.GoToNext, true | |
} else if _, ok := node.(*ast.Image); ok { | |
src := string(node.(*ast.Image).Destination) | |
c := node.(*ast.Image).GetChildren()[0] | |
alt := string(c.AsLeaf().Literal) | |
if entering && alt != "" { | |
w.Write([]byte(`<figure class="image is-5by3"><img src="` + src + `" alt="` + alt + `">`)) | |
} else if entering { | |
w.Write([]byte(`<figure class="image is-5by3"><img src="` + src + `">`)) | |
} else { | |
w.Write([]byte(`</figure>`)) | |
} | |
return ast.SkipChildren, true | |
} else { | |
return ast.GoToNext, false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment