wp-go/templates/templatefs.go

42 lines
925 B
Go
Raw Normal View History

2022-09-14 13:30:59 +00:00
package templates
2022-09-18 14:06:27 +00:00
import (
"embed"
"github.com/gin-gonic/gin/render"
"html/template"
2022-09-19 04:36:51 +00:00
"io/fs"
2022-09-18 14:06:27 +00:00
"path/filepath"
)
2022-09-14 13:30:59 +00:00
2022-09-18 04:34:48 +00:00
//go:embed posts layout
2022-09-14 13:30:59 +00:00
var TemplateFs embed.FS
2022-09-18 14:06:27 +00:00
type FsTemplate struct {
Templates map[string]*template.Template
FuncMap template.FuncMap
}
func NewFsTemplate(funcMap template.FuncMap) *FsTemplate {
return &FsTemplate{FuncMap: funcMap, Templates: make(map[string]*template.Template)}
}
2022-09-19 04:45:41 +00:00
func (t *FsTemplate) SetTemplate() *FsTemplate {
2022-09-19 04:36:51 +00:00
mainTemplates, err := fs.Glob(TemplateFs, "*[^layout]/*.gohtml")
if err != nil {
panic(err)
}
for _, include := range mainTemplates {
name := filepath.Base(include)
2022-09-19 04:38:36 +00:00
t.Templates[include] = template.Must(template.New(name).Funcs(t.FuncMap).ParseFS(TemplateFs, include, "layout/*.gohtml"))
2022-09-19 04:36:51 +00:00
}
2022-09-19 04:44:13 +00:00
return t
2022-09-18 14:06:27 +00:00
}
func (t FsTemplate) Instance(name string, data any) render.Render {
r := t.Templates[name]
return render.HTML{
Template: r,
2022-09-19 04:38:36 +00:00
Data: data,
2022-09-18 14:06:27 +00:00
}
}