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)
DefinedTemplates() string
Delims(left, right string) Template
Funcs(funcMap template.FuncMap) Template
Lookup(name string) Template
Name() string
New(name string) Template
Option(opt ...string) Template
Parse(text string) (Template, error)
ParseFS(fs fs.FS, patterns ...string) (Template, error)
ParseFiles(filenames ...string) (Template, error)
ParseGlob(pattern string) (Template, error)
Templates() []Template
Templater
}
type Templater interface {
Execute(wr io.Writer, data any) error
ExecuteTemplate(wr io.Writer, name string, data any) error
}