-
Notifications
You must be signed in to change notification settings - Fork 108
/
set.go
238 lines (212 loc) · 7.93 KB
/
set.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
package jet
import (
"errors"
"fmt"
"io/ioutil"
"path"
"path/filepath"
"reflect"
"sync"
"text/template"
)
// Set is responsible to load, parse and cache templates.
// Every Jet template is associated with a Set.
type Set struct {
loader Loader
cache Cache
escapee SafeWriter // escapee to use at runtime
globals VarMap // global scope for this template set
gmx *sync.RWMutex // global variables map mutex
extensions []string
developmentMode bool
leftDelim string
rightDelim string
leftComment string
rightComment string
}
// Option is the type of option functions that can be used in NewSet().
type Option func(*Set)
// NewSet returns a new Set relying on loader. NewSet panics if a nil Loader is passed.
func NewSet(loader Loader, opts ...Option) *Set {
if loader == nil {
panic(errors.New("jet: NewSet() must not be called with a nil loader"))
}
s := &Set{
loader: loader,
cache: &cache{},
escapee: template.HTMLEscape,
globals: VarMap{},
gmx: &sync.RWMutex{},
extensions: []string{
"", // in case the path is given with the correct extension already
".jet",
".html.jet",
".jet.html",
},
}
for _, opt := range opts {
opt(s)
}
return s
}
// WithCache returns an option function that sets the cache to use for template parsing results.
// Use InDevelopmentMode() to disable caching of parsed templates. By default, Jet uses a
// concurrency-safe in-memory cache that holds templates forever.
func WithCache(c Cache) Option {
if c == nil {
panic(errors.New("jet: WithCache() must not be called with a nil cache"))
}
return func(s *Set) {
s.cache = c
}
}
// WithSafeWriter returns an option function that sets the escaping function to use when executing
// templates. By default, Jet uses a writer that takes care of HTML escaping. Pass nil to disable escaping.
func WithSafeWriter(w SafeWriter) Option {
return func(s *Set) {
s.escapee = w
}
}
// WithDelims returns an option function that sets the delimiters to the specified strings.
// Parsed templates will inherit the settings. Not setting them leaves them at the default: `{{` and `}}`.
func WithDelims(left, right string) Option {
return func(s *Set) {
s.leftDelim = left
s.rightDelim = right
}
}
// WithCommentDelims returns an option function that sets the comment delimiters to the specified strings.
// Parsed templates will inherit the settings. Not setting them leaves them at the default: `{*` and `*}`.
func WithCommentDelims(left, right string) Option {
return func(s *Set) {
s.leftComment = left
s.rightComment = right
}
}
// WithTemplateNameExtensions returns an option function that sets the extensions to try when looking
// up template names in the cache or loader. Default extensions are `""` (no extension), `".jet"`,
// `".html.jet"`, `".jet.html"`. Extensions will be tried in the order they are defined in the slice.
// WithTemplateNameExtensions panics when you pass in a nil or empty slice.
func WithTemplateNameExtensions(extensions []string) Option {
if len(extensions) == 0 {
panic(errors.New("jet: WithTemplateNameExtensions() must not be called with a nil or empty slice of extensions"))
}
return func(s *Set) {
s.extensions = extensions
}
}
// InDevelopmentMode returns an option function that toggles development mode on, meaning the cache will
// always be bypassed and every template lookup will go to the loader.
func InDevelopmentMode() Option {
return DevelopmentMode(true)
}
// DevelopmentMode returns an option function that sets development mode on or off. "On" means the cache will
// always be bypassed and every template lookup will go to the loader.
func DevelopmentMode(mode bool) Option {
return func(s *Set) {
s.developmentMode = mode
}
}
// GetTemplate tries to find (and parse, if not yet parsed) the template at the specified path.
//
// For example, GetTemplate("catalog/products.list") with extensions set to []string{"", ".html.jet",".jet"}
// will try to look for:
// 1. catalog/products.list
// 2. catalog/products.list.html.jet
// 3. catalog/products.list.jet
// in the set's templates cache, and if it can't find the template it will try to load the same paths via
// the loader, and, if parsed successfully, cache the template (unless running in development mode).
func (s *Set) GetTemplate(templatePath string) (t *Template, err error) {
return s.getSiblingTemplate(templatePath, "/", true)
}
func (s *Set) getSiblingTemplate(templatePath, siblingPath string, cacheAfterParsing bool) (t *Template, err error) {
templatePath = filepath.ToSlash(templatePath)
siblingPath = filepath.ToSlash(siblingPath)
if !path.IsAbs(templatePath) {
siblingDir := path.Dir(siblingPath)
templatePath = path.Join(siblingDir, templatePath)
}
return s.getTemplate(templatePath, cacheAfterParsing)
}
// same as GetTemplate, but doesn't cache a template when found through the loader.
func (s *Set) getTemplate(templatePath string, cacheAfterParsing bool) (t *Template, err error) {
if !s.developmentMode {
t, found := s.getTemplateFromCache(templatePath)
if found {
return t, nil
}
}
t, err = s.getTemplateFromLoader(templatePath, cacheAfterParsing)
if err == nil && cacheAfterParsing && !s.developmentMode {
s.cache.Put(templatePath, t)
}
return t, err
}
func (s *Set) getTemplateFromCache(templatePath string) (t *Template, ok bool) {
// check path with all possible extensions in cache
for _, extension := range s.extensions {
canonicalPath := templatePath + extension
if t := s.cache.Get(canonicalPath); t != nil {
return t, true
}
}
return nil, false
}
func (s *Set) getTemplateFromLoader(templatePath string, cacheAfterParsing bool) (t *Template, err error) {
// check path with all possible extensions in loader
for _, extension := range s.extensions {
canonicalPath := templatePath + extension
if found := s.loader.Exists(canonicalPath); found {
return s.loadFromFile(canonicalPath, cacheAfterParsing)
}
}
return nil, fmt.Errorf("template %s could not be found", templatePath)
}
func (s *Set) loadFromFile(templatePath string, cacheAfterParsing bool) (template *Template, err error) {
f, err := s.loader.Open(templatePath)
if err != nil {
return nil, err
}
defer f.Close()
content, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
return s.parse(templatePath, string(content), cacheAfterParsing)
}
// Parse parses `contents` as if it were located at `templatePath`, but won't put the result into the cache.
// Any referenced template (e.g. via `extends` or `import` statements) will be tried to be loaded from the cache.
// If a referenced template has to be loaded and parsed, it will also not be put into the cache after parsing.
func (s *Set) Parse(templatePath, contents string) (template *Template, err error) {
templatePath = filepath.ToSlash(templatePath)
switch path.Base(templatePath) {
case ".", "/":
return nil, errors.New("template path has no base name")
}
// make sure it's absolute and clean it
templatePath = path.Join("/", templatePath)
return s.parse(templatePath, contents, false)
}
// AddGlobal adds a global variable into the Set,
// overriding any value previously set under the specified key.
// It returns the Set it was called on to allow for method chaining.
func (s *Set) AddGlobal(key string, i interface{}) *Set {
s.gmx.Lock()
defer s.gmx.Unlock()
s.globals[key] = reflect.ValueOf(i)
return s
}
// LookupGlobal returns the global variable previously set under the specified key.
// It returns the nil interface and false if no variable exists under that key.
func (s *Set) LookupGlobal(key string) (val interface{}, found bool) {
s.gmx.RLock()
defer s.gmx.RUnlock()
val, found = s.globals[key]
return
}
// AddGlobalFunc adds a global function into the Set,
// overriding any function previously set under the specified key.
// It returns the Set it was called on to allow for method chaining.
func (s *Set) AddGlobalFunc(key string, fn Func) *Set {
return s.AddGlobal(key, fn)
}