tulip/mail/templates/templates.go

56 lines
1.3 KiB
Go
Raw Permalink Normal View History

2023-09-24 18:24:16 +01:00
package templates
import (
"embed"
2023-10-09 20:31:41 +01:00
"errors"
"github.com/1f349/overlapfs"
htmlTemplate "html/template"
2023-09-24 18:24:16 +01:00
"io"
2023-10-09 20:31:41 +01:00
"io/fs"
2023-09-24 18:24:16 +01:00
"log"
2023-10-09 20:31:41 +01:00
"os"
"path/filepath"
"sync"
textTemplate "text/template"
2023-09-24 18:24:16 +01:00
)
var (
2023-10-09 20:31:41 +01:00
//go:embed *.go.html *.go.txt
2023-09-24 18:24:16 +01:00
embeddedTemplates embed.FS
2023-10-09 20:31:41 +01:00
mailHtmlTemplates *htmlTemplate.Template
mailTextTemplates *textTemplate.Template
loadOnce sync.Once
2023-09-24 18:24:16 +01:00
)
2023-10-09 20:31:41 +01:00
func LoadMailTemplates(wd string) (err error) {
loadOnce.Do(func() {
var o fs.FS = embeddedTemplates
if wd != "" {
mailDir := filepath.Join(wd, "mail-templates")
err = os.Mkdir(mailDir, os.ModePerm)
if err != nil && !errors.Is(err, os.ErrExist) {
return
}
wdFs := os.DirFS(mailDir)
o = overlapfs.OverlapFS{A: embeddedTemplates, B: wdFs}
}
mailHtmlTemplates, err = htmlTemplate.New("mail").ParseFS(o, "*.go.html")
if err != nil {
return
}
mailTextTemplates, err = textTemplate.New("mail").ParseFS(o, "*.go.txt")
})
2023-09-24 18:24:16 +01:00
return
}
2023-10-09 20:31:41 +01:00
func RenderMailTemplate(wrHtml, wrTxt io.Writer, name string, data any) {
err := mailHtmlTemplates.ExecuteTemplate(wrHtml, name+".go.html", data)
if err != nil {
log.Printf("Failed to render mail html: %s: %s\n", name, err)
}
err = mailTextTemplates.ExecuteTemplate(wrTxt, name+".go.txt", data)
2023-09-24 18:24:16 +01:00
if err != nil {
2023-10-09 20:31:41 +01:00
log.Printf("Failed to render mail text: %s: %s\n", name, err)
2023-09-24 18:24:16 +01:00
}
}