-
Notifications
You must be signed in to change notification settings - Fork 1
/
render.go
260 lines (223 loc) · 7.54 KB
/
render.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package render
import (
"bytes"
"encoding/json"
"fmt"
"github.com/codegangsta/martini"
"github.com/go-floki/jade"
"html/template"
"io"
// "io/ioutil"
"net/http"
"os"
"path/filepath"
)
const (
ContentType = "Content-Type"
ContentLength = "Content-Length"
ContentJSON = "application/json"
ContentHTML = "text/html"
defaultCharset = "UTF-8"
)
// Included helper functions for use when rendering html
var helperFuncs = template.FuncMap{
"yield": func() (string, error) {
return "", fmt.Errorf("yield called with no layout defined")
},
}
// Render is a service that can be injected into a Martini handler. Render provides functions for easily writing JSON and
// HTML templates out to a http Response.
type Render interface {
// JSON writes the given status and JSON serialized version of the given value to the http.ResponseWriter.
JSON(status int, v interface{})
// HTML renders a html template specified by the name and writes the result and given status to the http.ResponseWriter.
HTML(status int, name string, v interface{}, htmlOpt ...HTMLOptions)
// Error is a convenience function that writes an http status to the http.ResponseWriter.
Error(status int)
// Redirect is a convienience function that sends an HTTP redirect. If status is omitted, uses 302 (Found)
Redirect(location string, status ...int)
// Template returns the internal *template.Template used to render the HTML
Template() *template.Template
}
// Delims represents a set of Left and Right delimiters for HTML template rendering
type Delims struct {
// Left delimiter, defaults to {{
Left string
// Right delimiter, defaults to }}
Right string
}
// Options is a struct for specifying configuration options for the render.Renderer middleware
type Options struct {
// Directory to load templates. Default is "templates"
Directory string
// Layout template name. Will not render a layout if "". Defaults to "".
Layout string
// Extensions to parse template files from. Defaults to [".tmpl"]
Extensions []string
// Funcs is a slice of FuncMaps to apply to the template upon compilation. This is useful for helper functions. Defaults to [].
Funcs []template.FuncMap
// Delims sets the action delimiters to the specified strings in the Delims struct.
Delims Delims
// Appends the given charset to the Content-Type header. Default is "UTF-8".
Charset string
// Outputs human readable JSON
IndentJSON bool
}
// HTMLOptions is a struct for overriding some rendering Options for specific HTML call
type HTMLOptions struct {
// Layout template name. Overrides Options.Layout.
Layout string
}
// Renderer is a Middleware that maps a render.Render service into the Martini handler chain. An single variadic render.Options
// struct can be optionally provided to configure HTML rendering. The default directory for templates is "templates" and the default
// file extension is ".tmpl".
//
// If MARTINI_ENV is set to "" or "development" then templates will be recompiled on every request. For more performance, set the
// MARTINI_ENV environment variable to "production"
func Renderer(options ...Options) martini.Handler {
opt := prepareOptions(options)
cs := prepareCharset(opt.Charset)
t := compile(opt)
return func(res http.ResponseWriter, req *http.Request, c martini.Context) {
// recompile for easy development
if martini.Env == martini.Dev {
t = compile(opt)
}
tc, _ := t.Clone()
c.MapTo(&renderer{res, req, tc, opt, cs}, (*Render)(nil))
}
}
func prepareCharset(charset string) string {
if len(charset) != 0 {
return "; charset=" + charset
}
return "; charset=" + defaultCharset
}
func prepareOptions(options []Options) Options {
var opt Options
if len(options) > 0 {
opt = options[0]
}
// Defaults
if len(opt.Directory) == 0 {
opt.Directory = "templates"
}
if len(opt.Extensions) == 0 {
opt.Extensions = []string{".jade"}
}
return opt
}
func compile(options Options) *template.Template {
dir := options.Directory
t := template.New(dir)
t.Delims(options.Delims.Left, options.Delims.Right)
// parse an initial template in case we don't have any
template.Must(t.Parse("Martini"))
funcMap := template.FuncMap{}
// add our funcmaps
for _, funcs := range options.Funcs {
for k, v := range funcs {
funcMap[k] = v
}
}
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
r, err := filepath.Rel(dir, path)
if err != nil {
return err
}
ext := filepath.Ext(r)
for _, extension := range options.Extensions {
if ext == extension {
name := (r[0 : len(r)-len(ext)])
tmpl, err := jade.CompileFile(path, jade.Options{
Funcs: funcMap,
})
if err != nil {
panic(err)
}
t.Funcs(funcMap)
t.AddParseTree(filepath.ToSlash(name), tmpl.Tree)
break
}
}
return nil
})
return t
}
type renderer struct {
http.ResponseWriter
req *http.Request
t *template.Template
opt Options
compiledCharset string
}
func (r *renderer) JSON(status int, v interface{}) {
var result []byte
var err error
if r.opt.IndentJSON {
result, err = json.MarshalIndent(v, "", " ")
} else {
result, err = json.Marshal(v)
}
if err != nil {
http.Error(r, err.Error(), 500)
return
}
// json rendered fine, write out the result
r.Header().Set(ContentType, ContentJSON+r.compiledCharset)
r.WriteHeader(status)
r.Write(result)
}
func (r *renderer) HTML(status int, name string, binding interface{}, htmlOpt ...HTMLOptions) {
opt := r.prepareHTMLOptions(htmlOpt)
// assign a layout if there is one
if len(opt.Layout) > 0 {
r.addYield(name, binding)
name = opt.Layout
}
out, err := r.execute(name, binding)
if err != nil {
http.Error(r, err.Error(), http.StatusInternalServerError)
return
}
// template rendered fine, write out the result
r.Header().Set(ContentType, ContentHTML+r.compiledCharset)
r.WriteHeader(status)
io.Copy(r, out)
}
// Error writes the given HTTP status to the current ResponseWriter
func (r *renderer) Error(status int) {
r.WriteHeader(status)
}
func (r *renderer) Redirect(location string, status ...int) {
code := http.StatusFound
if len(status) == 1 {
code = status[0]
}
http.Redirect(r, r.req, location, code)
}
func (r *renderer) Template() *template.Template {
return r.t
}
func (r *renderer) execute(name string, binding interface{}) (*bytes.Buffer, error) {
buf := new(bytes.Buffer)
return buf, r.t.ExecuteTemplate(buf, name, binding)
}
func (r *renderer) addYield(name string, binding interface{}) {
funcs := template.FuncMap{
"yield": func() (template.HTML, error) {
buf, err := r.execute(name, binding)
// return safe html here since we are rendering our own template
return template.HTML(buf.String()), err
},
}
r.t.Funcs(funcs)
}
func (r *renderer) prepareHTMLOptions(htmlOpt []HTMLOptions) HTMLOptions {
if len(htmlOpt) > 0 {
return htmlOpt[0]
}
return HTMLOptions{
Layout: r.opt.Layout,
}
}