51 lines
994 B
Go
51 lines
994 B
Go
package template
|
|
|
|
import (
|
|
"embed"
|
|
"errors"
|
|
"fmt"
|
|
"html/template"
|
|
"io/fs"
|
|
|
|
"code.capytal.cc/loreddev/x/xtemplate"
|
|
)
|
|
|
|
func New() (xtemplate.Template, error) {
|
|
return xtemplate.New[template.Template]("template").
|
|
Funcs(functions).
|
|
ParseFS(embedded, patterns...)
|
|
}
|
|
|
|
//go:embed *.html layouts/*.html
|
|
var embedded embed.FS
|
|
|
|
func Dev(dir fs.FS) (xtemplate.Template, error) {
|
|
return xtemplate.NewHot[template.Template]("template").
|
|
Funcs(functions).
|
|
ParseFS(dir, patterns...)
|
|
}
|
|
|
|
var (
|
|
patterns = []string{"*.html", "layouts/*.html"}
|
|
functions = template.FuncMap{
|
|
"args": func(pairs ...any) (map[string]any, error) {
|
|
if len(pairs)%2 != 0 {
|
|
return nil, errors.New("misaligned map in template arguments")
|
|
}
|
|
|
|
m := make(map[string]any, len(pairs)/2)
|
|
|
|
for i := 0; i < len(pairs); i += 2 {
|
|
key, ok := pairs[i].(string)
|
|
if !ok {
|
|
return nil, fmt.Errorf("cannot use type %T as map key", pairs[i])
|
|
}
|
|
|
|
m[key] = pairs[i+1]
|
|
}
|
|
|
|
return m, nil
|
|
},
|
|
}
|
|
)
|