wp-go/internal/theme/fs.go

68 lines
1.4 KiB
Go
Raw Normal View History

package theme
2022-09-14 13:30:59 +00:00
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-11-04 04:22:56 +00:00
"strings"
2022-09-18 14:06:27 +00:00
)
2022-09-14 13:30:59 +00:00
//go:embed *[^.go]
2022-09-14 13:30:59 +00:00
var TemplateFs embed.FS
2022-09-18 14:06:27 +00:00
2023-01-20 11:58:45 +00:00
var templates map[string]*template.Template
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 {
2023-01-20 11:58:45 +00:00
templates = make(map[string]*template.Template)
return &FsTemplate{FuncMap: funcMap, Templates: templates}
2022-09-18 14:06:27 +00:00
}
2022-11-04 04:59:52 +00:00
func (t FsTemplate) SetTemplate() *FsTemplate {
2022-11-04 04:22:56 +00:00
mainTemplates, err := fs.Glob(TemplateFs, `*/*[^layout]/*.gohtml`)
2022-09-19 04:36:51 +00:00
if err != nil {
panic(err)
}
for _, include := range mainTemplates {
name := filepath.Base(include)
2022-11-04 04:22:56 +00:00
c := strings.Split(include, "/")
base := c[0]
2022-11-04 04:25:00 +00:00
t.Templates[include] = template.Must(template.New(name).Funcs(t.FuncMap).ParseFS(TemplateFs, include, filepath.Join(base, "layout/*.gohtml")))
2022-09-19 04:36:51 +00:00
}
2022-11-04 04:59:52 +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
}
}
2023-01-14 04:21:31 +00:00
2023-01-20 11:58:45 +00:00
func IsTemplateDirExists(tml string) bool {
2023-01-14 04:21:31 +00:00
arr, err := TemplateFs.ReadDir(tml)
if err != nil {
2023-01-20 11:58:45 +00:00
return false
2023-01-14 04:21:31 +00:00
}
if len(arr) > 0 {
2023-01-20 11:58:45 +00:00
return true
2023-01-14 04:21:31 +00:00
}
2023-01-20 11:58:45 +00:00
return false
}
func IsTemplateExists(tml string) bool {
t, ok := templates[tml]
return ok && t != nil
}
func GetTemplate(tml string) *template.Template {
return templates[tml]
2023-01-14 04:21:31 +00:00
}