wp-go/internal/theme/fs.go

56 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"
2023-01-21 06:49:24 +00:00
"github.com/fthvgb1/wp-go/multipTemplate"
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
2023-01-21 06:49:24 +00:00
var templates map[string]*template.Template //方便外部获取模板render后的字符串不然在gin中获取不了
2023-01-20 11:58:45 +00:00
2023-01-21 06:49:24 +00:00
func GetTemplate() *multipTemplate.MultipleFsTemplate {
t := multipTemplate.NewFsTemplate(TemplateFs)
templates = t.Template
t.FuncMap = FuncMap()
commonTemplate(t)
/*t.AddTemplate("twentyfifteen/*[^layout]/*.gohtml", FuncMap(), "twentyfifteen/layout/*.gohtml"). //单个主题设置
AddTemplate("twentyseventeen/*[^layout]/*.gohtml", FuncMap(), "twentyseventeen/layout/*.gohtml")*/
return t
2022-09-18 14:06:27 +00:00
}
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)
}
2023-01-21 06:49:24 +00:00
for _, main := range m {
file := filepath.Base(main)
dir := strings.Split(main, "/")[0]
2023-03-01 05:17:12 +00:00
templ := template.Must(template.New(file).Funcs(t.FuncMap).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[tml]
return ok && t != nil
}