diff wdown.go @ 6:a5f397e25cb7

Add ability to render the markdown inside a template
author Jonatan Werpers <jonatan@werpers.com>
date Tue, 16 Jun 2020 22:10:31 +0200
parents 534fa4c6668e
children a5aa39557726
line wrap: on
line diff
--- a/wdown.go	Tue Jun 16 21:23:38 2020 +0200
+++ b/wdown.go	Tue Jun 16 22:10:31 2020 +0200
@@ -1,12 +1,14 @@
 package main
 
 import (
+	"bytes"
 	"flag"
 	"fmt"
 	"io/ioutil"
 	"log"
 	"os"
 
+	"github.com/cbroglie/mustache"
 	"github.com/yuin/goldmark"
 	highlighting "github.com/yuin/goldmark-highlighting"
 	"github.com/yuin/goldmark/extension"
@@ -14,6 +16,10 @@
 )
 
 func main() {
+	var templateFilename string
+
+	flag.StringVar(&templateFilename, "tmpl", "", "Template file to render the html inside. The content of the markdown file will replace the placeholder {{content}}.")
+
 	flag.Parse()
 
 	if flag.NArg() < 1 {
@@ -21,6 +27,16 @@
 		os.Exit(1)
 	}
 
+	var useTemplate = false
+	if templateFilename != "" {
+		useTemplate = true
+	}
+
+	tmpl, err := mustache.ParseFile(templateFilename)
+	if err != nil {
+		log.Fatal(err)
+	}
+
 	source, err := ioutil.ReadFile(flag.Arg(0))
 
 	if err != nil {
@@ -37,9 +53,21 @@
 		),
 	)
 
-	err = md.Convert(source, os.Stdout)
-
+	var htmlContent bytes.Buffer
+	err = md.Convert(source, &htmlContent)
 	if err != nil {
 		log.Fatal(err)
 	}
+
+	if useTemplate {
+		context := map[string]string{
+			"content": htmlContent.String(),
+		}
+		err := tmpl.FRender(os.Stdout, context)
+		if err != nil {
+			log.Fatal(err)
+		}
+	} else {
+		fmt.Print(htmlContent)
+	}
 }