owl-blogs/render/templates.go

103 lines
2.0 KiB
Go
Raw Permalink Normal View History

2023-07-09 17:51:49 +00:00
package render
import (
"bytes"
"embed"
"io"
2024-02-24 20:21:48 +00:00
"net/url"
2023-07-16 19:48:39 +00:00
"owl-blogs/domain/model"
2023-07-09 17:51:49 +00:00
"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
)
2023-07-16 19:48:39 +00:00
type TemplateData struct {
Data interface{}
SiteConfig model.SiteConfig
}
2023-07-09 17:51:49 +00:00
//go:embed templates
var templates embed.FS
var SiteConfigService model.SiteConfigInterface
2023-07-09 17:51:49 +00:00
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
},
2024-02-24 20:21:48 +00:00
"urljoin": func(elems ...string) string {
r, _ := url.JoinPath(elems[0], elems[1:]...)
return r
},
2023-07-13 18:39:24 +00:00
}
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 {
2023-07-09 17:51:49 +00:00
t, err := CreateTemplateWithBase(templateName)
if err != nil {
return err
}
siteConfig, err := SiteConfigService.GetSiteConfig()
if err != nil {
return err
}
2023-07-16 19:48:39 +00:00
err = t.ExecuteTemplate(w, "base", TemplateData{
Data: data,
2023-07-17 18:44:59 +00:00
SiteConfig: siteConfig,
2023-07-16 19:48:39 +00:00
})
2023-07-09 17:51:49 +00:00
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
}