/
h_template.go
63 lines (52 loc) · 1.21 KB
/
h_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
package webutil
import (
"context"
"fmt"
"html/template"
"net/http"
"github.com/noypi/router"
)
type _templateType int
const TPLRootKey _templateType = 0
var ErrNoRootTPL = fmt.Errorf("no root template found.")
func GetRootTPL(ctx context.Context) *template.Template {
c := ToStore(ctx)
if t, b := c.Get(TPLRootKey); b {
return t.(*template.Template)
}
return nil
}
func SetRootTemplate(ctx context.Context, tpl *template.Template) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c := ToStore(ctx)
c.Set(TPLRootKey, tpl)
}
}
func AddGlobToRootTPL(pattern string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c := router.ContextW(w)
roottpl := GetRootTPL(c)
if nil == roottpl {
AddError(c, ErrNoRootTPL)
return
}
if _, err := roottpl.ParseGlob(pattern); nil != err {
AddError(c, err)
return
}
}
}
func AddFilesToRootTPL(filenames ...string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c := router.ContextW(w)
roottpl := GetRootTPL(c)
if nil == roottpl {
AddError(c, ErrNoRootTPL)
return
}
if _, err := roottpl.ParseFiles(filenames...); nil != err {
AddError(c, err)
return
}
}
}