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-11-04 04:22:56 +00:00
|
|
|
"strings"
|
2022-09-18 14:06:27 +00:00
|
|
|
)
|
2022-09-14 13:30:59 +00:00
|
|
|
|
2022-11-04 02:54:07 +00:00
|
|
|
//go:embed twentyfifteen
|
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-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-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
|
|
|
}
|
|
|
|
}
|