view 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 source

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"
	"github.com/yuin/goldmark/parser"
)

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 {
		fmt.Println("Please provide a markdown file for parsing.")
		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 {
		log.Fatal(err)
	}

	md := goldmark.New(
		goldmark.WithExtensions(
			extension.GFM,
			highlighting.Highlighting,
		),
		goldmark.WithParserOptions(
			parser.WithAutoHeadingID(),
		),
	)

	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)
	}
}