owl-blogs/render/templates.go

83 lines
1.6 KiB
Go
Raw Normal View History

2023-07-09 17:51:49 +00:00
package render
import (
"bytes"
"embed"
"io"
"text/template"
2023-07-13 18:39:24 +00:00
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/renderer/html"
2023-07-09 17:51:49 +00:00
)
//go:embed templates
var templates embed.FS
2023-07-13 18:39:24 +00:00
var funcMap = template.FuncMap{
"markdown": func(text string) string {
html, err := RenderMarkdown(text)
if err != nil {
return ">>>could not render markdown<<<"
}
return html
},
}
2023-07-09 17:51:49 +00:00
func CreateTemplateWithBase(templateName string) (*template.Template, error) {
2023-07-13 18:39:24 +00:00
return template.New(templateName).Funcs(funcMap).ParseFS(
2023-07-09 17:51:49 +00:00
templates,
"templates/base.tmpl",
"templates/"+templateName+".tmpl",
)
}
func RenderTemplateWithBase(w io.Writer, templateName string, data interface{}) error {
t, err := CreateTemplateWithBase(templateName)
if err != nil {
return err
}
err = t.ExecuteTemplate(w, "base", data)
return err
}
func RenderTemplateToString(templateName string, data interface{}) (string, error) {
2023-07-13 18:39:24 +00:00
tmplStr, _ := templates.ReadFile("templates/" + templateName + ".tmpl")
2023-07-09 17:51:49 +00:00
2023-07-13 18:39:24 +00:00
t, err := template.New("templates/" + templateName + ".tmpl").Funcs(funcMap).Parse(string(tmplStr))
2023-07-09 17:51:49 +00:00
if err != nil {
return "", err
}
var output bytes.Buffer
err = t.Execute(&output, data)
return output.String(), err
}
2023-07-13 18:39:24 +00:00
func RenderMarkdown(mdText string) (string, error) {
markdown := goldmark.New(
goldmark.WithRendererOptions(
html.WithUnsafe(),
),
goldmark.WithExtensions(
// meta.Meta,
extension.GFM,
),
)
var buf bytes.Buffer
context := parser.NewContext()
err := markdown.Convert([]byte(mdText), &buf, parser.WithContext(context))
return buf.String(), err
}