-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
61 lines (52 loc) · 1.54 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
package mngr
import (
"context"
"html/template"
"net/http"
"strings"
"github.com/russross/blackfriday"
)
type (
templateCtxKey int
// TemplateInfo contains the field common to every template.
TemplateInfo struct {
Action string
Value string
Dir string
IsDir bool
}
)
var templateKey = templateCtxKey(0)
func NewTemplateFromValidURL(v ValidURL) TemplateInfo {
return TemplateInfo{
Action: v.Action,
Value: v.Value,
Dir: v.Dir,
}
}
// TemplateFromCtx extract templates added by MakeTemplateMiddleware to a context.
func TemplateFromCtx(c context.Context) (*template.Template, bool) {
t, ok := c.Value(templateKey).(*template.Template)
return t, ok
}
// MakeTemplateMiddleware load an compile all templates located in 'path/*.html' and 'path/partial/*.html'.
// When plugged, the returned middleware add templates to the request's context.
func MakeTemplateMiddleware(path string) Middleware {
var tmplFunc = template.FuncMap{
"renderMD": func(data []byte) template.HTML {
return template.HTML(blackfriday.MarkdownCommon(data))
},
"fmtTitle": func(title string) string {
return strings.Title(title)
},
}
templates := template.Must(template.New("main").Funcs(tmplFunc).ParseGlob(path + "/*.html"))
templates = template.Must(templates.ParseGlob(path + "/partial/*.html"))
return func(h Handler) Handler {
return HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
ctx := r.Context()
ctx = context.WithValue(ctx, templateKey, templates)
return h.ServeHTTP(w, r.WithContext(ctx))
})
}
}