feat(xtemplate): Template interface constructors based on text/ and html/template

This commit is contained in:
Guz
2025-10-21 21:45:49 -03:00
parent 997be04fc1
commit 0281e7ac20

View File

@@ -1,11 +1,74 @@
package xtemplate
import (
htmltemplate "html/template"
"io"
"io/fs"
"text/template"
"text/template/parse"
)
func Must(t Template, err error) Template {
if err != nil {
panic(err)
}
return t
}
func New[T template.Template | htmltemplate.Template](name string) Template {
var t T
switch any(t).(type) {
case template.Template:
return &textTemplate{template.New(name)}
case htmltemplate.Template:
return &htmlTemplate{htmltemplate.New(name)}
default:
panic("Incorrect T type")
}
}
func ParseFS[T template.Template | htmltemplate.Template](fs fs.FS, patterns ...string) (Template, error) {
var t T
switch any(t).(type) {
case template.Template:
temp, err := template.ParseFS(fs, patterns...)
return &textTemplate{temp}, err
case htmltemplate.Template:
temp, err := htmltemplate.ParseFS(fs, patterns...)
return &htmlTemplate{temp}, err
default:
panic("Incorrect T type")
}
}
func ParseFiles[T template.Template | htmltemplate.Template](filenames ...string) (Template, error) {
var t T
switch any(t).(type) {
case template.Template:
temp, err := template.ParseFiles(filenames...)
return &textTemplate{temp}, err
case htmltemplate.Template:
temp, err := htmltemplate.ParseFiles(filenames...)
return &htmlTemplate{temp}, err
default:
panic("Incorrect T type")
}
}
func ParseGlob[T template.Template | htmltemplate.Template](pattern string) (Template, error) {
var t T
switch any(t).(type) {
case template.Template:
temp, err := template.ParseGlob(pattern)
return &textTemplate{temp}, err
case htmltemplate.Template:
temp, err := htmltemplate.ParseGlob(pattern)
return &htmlTemplate{temp}, err
default:
panic("Incorrect T type")
}
}
type Template interface {
AddParseTree(name string, tree *parse.Tree) (Template, error)
Clone() (Template, error)