forked from gobuffalo/buffalo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
94 lines (79 loc) · 2.18 KB
/
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package render
import (
"html"
"html/template"
"io"
"path/filepath"
"strings"
"github.com/shurcooL/github_flavored_markdown"
)
type templateRenderer struct {
*Engine
contentType string
names []string
}
func (s templateRenderer) ContentType() string {
return s.contentType
}
func (s templateRenderer) Render(w io.Writer, data Data) error {
var body template.HTML
var err error
for _, name := range s.names {
body, err = s.exec(name, data)
if err != nil {
return err
}
data["yield"] = body
}
w.Write([]byte(body))
return nil
}
func (s templateRenderer) partial(name string, dd Data) (template.HTML, error) {
d, f := filepath.Split(name)
name = filepath.Join(d, "_"+f)
return s.exec(name, dd)
}
func (s templateRenderer) exec(name string, data Data) (template.HTML, error) {
source, err := s.TemplatesBox.MustBytes(name)
if err != nil {
return "", err
}
helpers := map[string]interface{}{
"partial": s.partial,
}
for k, v := range s.Helpers {
helpers[k] = v
}
if strings.ToLower(filepath.Ext(name)) == ".md" {
source = github_flavored_markdown.Markdown(source)
source = []byte(html.UnescapeString(string(source)))
}
body, err := s.TemplateEngine(string(source), data, helpers)
if err != nil {
return "", err
}
return template.HTML(body), nil
}
// Template renders the named files using the specified
// content type and the github.com/gobuffalo/plush
// package for templating. If more than 1 file is provided
// the second file will be considered a "layout" file
// and the first file will be the "content" file which will
// be placed into the "layout" using "{{yield}}".
func Template(c string, names ...string) Renderer {
e := New(Options{})
return e.Template(c, names...)
}
// Template renders the named files using the specified
// content type and the github.com/gobuffalo/plush
// package for templating. If more than 1 file is provided
// the second file will be considered a "layout" file
// and the first file will be the "content" file which will
// be placed into the "layout" using "{{yield}}".
func (e *Engine) Template(c string, names ...string) Renderer {
return templateRenderer{
Engine: e,
contentType: c,
names: names,
}
}