goveal/rendering/templates.go
Peter Kurfer 7d3d3a5abf
Split slides first before rendering them
- add some more config options
- cleanup code
- remove state machine
2021-12-22 22:31:45 +01:00

61 lines
1.5 KiB
Go

package rendering
import (
"bytes"
"embed"
"hash/fnv"
"html/template"
"sync"
"github.com/Masterminds/sprig/v3"
"github.com/gomarkdown/markdown"
mdhtml "github.com/gomarkdown/markdown/html"
"github.com/gomarkdown/markdown/parser"
)
var (
//go:embed templates/*.gohtml
templatesFS embed.FS
templates *template.Template
templateRenderBufferPool = &sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
)
func init() {
templates = template.New("rendering").
Funcs(sprig.FuncMap()).
Funcs(template.FuncMap{
"renderMarkdown": func(md string) template.HTML {
rr := &RevealRenderer{
Hash: fnv.New32a(),
}
mdParser := parser.NewWithExtensions(parserExtensions)
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)
}
}
func renderTemplate(templateName string, data interface{}) (output []byte, err error) {
buffer := templateRenderBufferPool.Get().(*bytes.Buffer)
defer func() {
buffer.Reset()
templateRenderBufferPool.Put(buffer)
}()
err = templates.ExecuteTemplate(buffer, templateName, data)
return buffer.Bytes(), err
}