app/email/engine.go

88 lines
1.6 KiB
Go

package email
import (
"bytes"
_ "embed"
"html/template"
"strings"
"github.com/vanng822/go-premailer/premailer"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
)
//go:embed base.gohtml
var mailTmpl string
var engine *template.Template
var app App
var mdParser = goldmark.New(
goldmark.WithExtensions(extension.GFM),
)
func init() {
engine = template.Must(template.New("email").Funcs(template.FuncMap{
"ToHTML": ToHTML,
"add": func(a, b int) int {
return a + b
},
"mul": func(a, b int) int {
return a * b
},
"replace": func(from, to, input string) string {
return strings.Replace(input, from, to, -1)
},
}).Parse(mailTmpl))
}
func ToHTML(mdtext string) (template.HTML, error) {
var buf bytes.Buffer
if err := mdParser.Convert([]byte(mdtext), &buf); err != nil {
return "", err
}
return template.HTML(buf.String()), nil
}
func Parse(b *Body) (string, error) {
merge(&b.App)
buf := &bytes.Buffer{}
err := engine.Execute(buf, b)
if err != nil {
return "", err
}
pre, err := premailer.NewPremailerFromString(buf.String(), premailer.NewOptions())
if err != nil {
return "", err
}
html, err := pre.Transform()
return html, err
}
func merge(base *App) {
if base.Name == "" {
base.Name = app.Name
}
if base.Link == "" {
base.Link = app.Link
}
if base.Logo == "" {
base.Logo = app.Logo
}
if base.Copyright == "" {
base.Copyright = app.Copyright
}
if base.TroubleText == "" {
base.TroubleText = app.TroubleText
}
if base.Theme == "" {
base.Theme = app.Theme
}
if base.TitleColor == "" {
base.TitleColor = app.TitleColor
}
if base.FooterColor == "" {
base.FooterColor = app.FooterColor
}
}