Files
complie-erlang/template/template_engine.go
T
2025-09-24 00:54:08 +08:00

56 lines
1.0 KiB
Go

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
}