wp-go/app/theme/fs.go

83 lines
2.1 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"
2023-01-21 06:49:24 +00:00
"github.com/fthvgb1/wp-go/multipTemplate"
"github.com/fthvgb1/wp-go/safety"
2022-09-18 14:06:27 +00:00
"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
var templates = safety.NewMap[string, *template.Template]() //方便外部获取模板render后的字符串不然在gin中获取不了
2023-01-20 11:58:45 +00:00
var multiple *multipTemplate.MultipleFsTemplate
func BuildTemplate() *multipTemplate.MultipleFsTemplate {
if multiple != nil {
tt := multipTemplate.NewFsTemplate(TemplateFs)
commonTemplate(tt)
for k, v := range map[string]*template.Template(any(tt.Template).(multipTemplate.TemplateMaps)) {
multiple.Template.Store(k, v)
}
} else {
multiple = multipTemplate.NewFsTemplates(TemplateFs, templates)
commonTemplate(multiple)
}
/*t.AddTemplate("twentyfifteen/*[^layout]/*.gohtml", FuncMap(), "twentyfifteen/layout/*.gohtml","wp/template.gohtml"). //单个主题设置
AddTemplate("twentyseventeen/*[^layout]/*.gohtml", FuncMap(), "twentyseventeen/layout/*.gohtml","wp/template.gohtml")*/
return multiple
}
func GetMultipleTemplate() *multipTemplate.MultipleFsTemplate {
if multiple == nil {
BuildTemplate()
}
return multiple
2022-09-18 14:06:27 +00:00
}
2023-03-09 14:36:41 +00:00
func GetTemplate(name string) (*template.Template, bool) {
t, ok := templates.Load(name)
2023-03-09 14:36:41 +00:00
return t, ok
}
2023-01-21 06:49:24 +00:00
// 所有主题模板通用设置
func commonTemplate(t *multipTemplate.MultipleFsTemplate) {
m, err := fs.Glob(t.Fs, "*/posts/*.gohtml")
2022-09-19 04:36:51 +00:00
if err != nil {
panic(err)
}
2024-01-23 16:25:37 +00:00
funMap := FuncMap()
2023-01-21 06:49:24 +00:00
for _, main := range m {
file := filepath.Base(main)
dir := strings.Split(main, "/")[0]
2024-01-23 16:25:37 +00:00
templ := template.Must(template.New(file).Funcs(funMap).ParseFS(t.Fs, main, filepath.Join(dir, "layout/*.gohtml"), "wp/template.gohtml"))
2023-01-21 06:49:24 +00:00
t.SetTemplate(main, templ)
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.Load(tml)
2023-01-20 11:58:45 +00:00
return ok && t != nil
}
func SetTemplate(name string, val *template.Template) {
templates.Store(name, val)
}