wp-go/templates/templatefs.go

44 lines
1001 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:36:51 +00:00
func (t *FsTemplate) AddTemplate() {
mainTemplates, err := fs.Glob(TemplateFs, "*[^layout]/*.gohtml")
if err != nil {
panic(err)
}
for _, include := range mainTemplates {
name := filepath.Base(include)
in := append([]string{include}, "layout/*.gohtml")
//n := strings.Replace(name, ".gohtml", "", -1)
t.Templates[include] = template.Must(template.New(name).Funcs(t.FuncMap).ParseFS(TemplateFs, in...))
}
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:36:51 +00:00
//Name: name,
Data: data,
2022-09-18 14:06:27 +00:00
}
}