补充完成逻辑
This commit is contained in:
+15
-26
@@ -1,14 +1,12 @@
|
||||
package template
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
type Template struct {
|
||||
Templates map[string]*template.Template
|
||||
GlobTemplate *template.Template
|
||||
}
|
||||
|
||||
var DefaultFuncMap = template.FuncMap{
|
||||
@@ -23,33 +21,24 @@ func hd(str []string) string {
|
||||
}
|
||||
|
||||
func NewTemplate() *Template {
|
||||
return &Template{
|
||||
Templates: make(map[string]*template.Template),
|
||||
}
|
||||
return &Template{}
|
||||
}
|
||||
|
||||
func (t *Template) Load(dir string) error {
|
||||
files, err := os.ReadDir(dir)
|
||||
func (t *Template) ParseGlob(pattern string) error {
|
||||
parse, err := template.New("").
|
||||
Funcs(DefaultFuncMap).ParseGlob(pattern)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, file := range files {
|
||||
if file.IsDir() {
|
||||
continue
|
||||
}
|
||||
if strings.HasSuffix(file.Name(), ".tpl") {
|
||||
templateName := strings.TrimSuffix(file.Name(), ".tpl")
|
||||
path := filepath.Join(dir, file.Name())
|
||||
bytes, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parse, err := template.New(templateName).Funcs(DefaultFuncMap).Parse(string(bytes))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.Templates[templateName] = parse
|
||||
}
|
||||
}
|
||||
t.GlobTemplate = template.Must(parse, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Template) ExecuteTemplate(templateName2 string, data interface{}) (string, error) {
|
||||
var buf strings.Builder
|
||||
err := t.GlobTemplate.ExecuteTemplate(&buf, templateName2, data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user