wp-go/templates/templatefs.go
2022-11-04 12:22:56 +08:00

46 lines
1018 B
Go

package templates
import (
"embed"
"fmt"
"github.com/gin-gonic/gin/render"
"html/template"
"io/fs"
"path/filepath"
"strings"
)
//go:embed twentyfifteen
var TemplateFs embed.FS
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)}
}
func (t *FsTemplate) SetTemplate() *FsTemplate {
mainTemplates, err := fs.Glob(TemplateFs, `*/*[^layout]/*.gohtml`)
if err != nil {
panic(err)
}
for _, include := range mainTemplates {
name := filepath.Base(include)
c := strings.Split(include, "/")
base := c[0]
t.Templates[include] = template.Must(template.New(name).Funcs(t.FuncMap).ParseFS(TemplateFs, include, fmt.Sprintf("%s/layout/*.gohtml", base)))
}
return t
}
func (t FsTemplate) Instance(name string, data any) render.Render {
r := t.Templates[name]
return render.HTML{
Template: r,
Data: data,
}
}