初版提交
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
package template
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
type Template struct {
|
||||
Templates map[string]*template.Template
|
||||
}
|
||||
|
||||
var DefaultFuncMap = template.FuncMap{
|
||||
"hd": hd,
|
||||
"title": strings.Title,
|
||||
"join": strings.Join,
|
||||
"list": func(strs []string) string { return strings.Join(strs, ",") },
|
||||
}
|
||||
|
||||
func hd(str []string) string {
|
||||
return str[0]
|
||||
}
|
||||
|
||||
func NewTemplate() *Template {
|
||||
return &Template{
|
||||
Templates: make(map[string]*template.Template),
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Template) Load(dir string) error {
|
||||
files, err := os.ReadDir(dir)
|
||||
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
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user