~gjabell/mfn

ref: 298287072d83612d77b1acee812a011f045ac5b3 mfn/template.go -rw-r--r-- 1.0 KiB
29828707Galen Abell Add HTML option for email and webhook 1 year, 6 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main

import (
	html "html/template"
	"io"
	text "text/template"
)

// Templater delegates calls to either text.Template or html.Template
// type Templater interface {
// 	Parse(string) (*Template, error)
// 	Execute(io.Writer, interface{}) error
// }

// Template is a wrapper around text and html templates
type Template struct {
	name         string
	html         bool
	textTemplate *text.Template
	htmlTemplate *html.Template
}

func NewTemplate(name string, html bool) *Template {
	return &Template{
		name: name,
		html: html,
	}
}

func (t *Template) Parse(template string) (*Template, error) {
	if t.html {
		tmpl, err := text.New(t.name).Parse(template)
		if err != nil {
			return nil, err
		}

		t.textTemplate = tmpl
		return t, nil
	}

	tmpl, err := html.New(t.name).Parse(template)
	if err != nil {
		return nil, err
	}

	t.htmlTemplate = tmpl
	return t, nil
}

func (t *Template) Execute(wr io.Writer, data interface{}) error {
	if t.html {
		return t.textTemplate.Execute(wr, data)
	}

	return t.htmlTemplate.Execute(wr, data)
}