/
html_template.go
65 lines (56 loc) · 1.18 KB
/
html_template.go
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
57
58
59
60
61
62
63
64
65
package damsel
import (
"bytes"
"html/template"
"dasa.cc/damsel/parse"
)
var (
LeftDelim = "{"
RightDelim = "}"
funcMap = template.FuncMap{
"Mod": Mod,
"StrEq": StrEq,
}
)
func Delims(l, r string) {
LeftDelim = l
RightDelim = r
}
// Mod provides a modulus function to html/template.
func Mod(i, n int) bool {
if (i % n) == 0 {
return true
}
return false
}
// StrEq provides string equality check to html/template.
func StrEq(a, b string) bool {
return a == b
}
// HtmlTemplate is an inefficient example of external template integration that is also used with tests
// using html/template.
type HtmlTemplate struct {
Html *template.Template
Dmsl *Template
}
func NewHtmlTemplate(tpl *Template) *HtmlTemplate {
t := &HtmlTemplate{}
t.Html = template.New("").Delims(LeftDelim, RightDelim).Funcs(funcMap)
t.Dmsl = tpl
return t
}
func (t *HtmlTemplate) Execute(data interface{}) (string, error) {
_, err := t.Html.Parse(string(t.Dmsl.ParseResult()))
if err != nil {
return "", err
}
buf := &bytes.Buffer{}
if err := t.Html.Execute(buf, data); err != nil {
return "", err
}
r, err := parse.DocParse(buf.Bytes())
if err != nil {
return "", err
}
return r, nil
}