goveal/rendering/templates.go

61 lines
1.5 KiB
Go
Raw Normal View History

package rendering
import (
"embed"
"hash/fnv"
"html/template"
"github.com/Masterminds/sprig/v3"
"github.com/gomarkdown/markdown"
mdhtml "github.com/gomarkdown/markdown/html"
"github.com/gomarkdown/markdown/parser"
2022-03-15 19:22:04 +00:00
"github.com/valyala/bytebufferpool"
2022-03-15 14:44:53 +00:00
2022-09-25 12:23:22 +00:00
"code.icb4dc0.de/prskr/goveal/rendering/emoji"
)
var (
//go:embed templates/*.gohtml
2022-03-15 19:22:04 +00:00
templatesFS embed.FS
templates *template.Template
)
func init() {
templates = template.New("rendering").
Funcs(sprig.FuncMap()).
Funcs(template.FuncMap{
"renderMarkdown": func(md string) template.HTML {
rr := &RevealRenderer{
Hash: fnv.New32a(),
}
2022-03-15 14:44:53 +00:00
emojis := emoji.NewEmojiParser()
mdParser := parser.NewWithExtensions(parserExtensions)
2022-03-15 14:44:53 +00:00
mdParser.Opts.ParserHook = emojis.EmojiParser
renderer := mdhtml.NewRenderer(mdhtml.RendererOptions{
Flags: mdhtml.CommonFlags | mdhtml.HrefTargetBlank,
RenderNodeHook: rr.RenderHook,
})
renderedHTML := markdown.ToHTML([]byte(md), mdParser, renderer)
//nolint:gosec // template should be esacped
return template.HTML(renderedHTML)
},
})
var err error
if templates, err = templates.ParseFS(templatesFS, "templates/*.gohtml"); err != nil {
panic(err)
}
}
2022-03-15 19:22:04 +00:00
func renderTemplate(templateName string, data any) (output []byte, err error) {
buffer := bytebufferpool.Get()
defer func() {
buffer.Reset()
2022-03-15 19:22:04 +00:00
bytebufferpool.Put(buffer)
}()
err = templates.ExecuteTemplate(buffer, templateName, data)
return buffer.Bytes(), err
}