34 lines
1.1 KiB
Go
34 lines
1.1 KiB
Go
|
|
package smtp
|
||
|
|
|
||
|
|
import (
|
||
|
|
"html/template"
|
||
|
|
"io/fs"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
"code.nochebuena.dev/einherjar/core/xerrors"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Template wraps stdlib html/template for HTML email rendering.
|
||
|
|
// Rendering is intentionally separate from [Sender.Send] — callers render
|
||
|
|
// a template to a string and assign it to [Message.Body].
|
||
|
|
type Template struct{ t *template.Template }
|
||
|
|
|
||
|
|
// ParseFS parses the named pattern files from fsys into a Template.
|
||
|
|
// Returns an error if any pattern matches no files or a file fails to parse.
|
||
|
|
func ParseFS(fsys fs.FS, patterns ...string) (*Template, error) {
|
||
|
|
t, err := template.ParseFS(fsys, patterns...)
|
||
|
|
if err != nil {
|
||
|
|
return nil, xerrors.New(xerrors.ErrInvalidInput, "smtp: parse template").WithError(err)
|
||
|
|
}
|
||
|
|
return &Template{t: t}, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// Render executes the named template with data and returns the rendered string.
|
||
|
|
func (t *Template) Render(name string, data any) (string, error) {
|
||
|
|
var buf strings.Builder
|
||
|
|
if err := t.t.ExecuteTemplate(&buf, name, data); err != nil {
|
||
|
|
return "", xerrors.New(xerrors.ErrInternal, "smtp: render template").WithError(err)
|
||
|
|
}
|
||
|
|
return buf.String(), nil
|
||
|
|
}
|