-
Notifications
You must be signed in to change notification settings - Fork 632
/
environment.js
621 lines (529 loc) · 14.8 KB
/
environment.js
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
'use strict';
var path = require('path');
var asap = require('asap');
var lib = require('./lib');
var Obj = require('./object');
var compiler = require('./compiler');
var builtin_filters = require('./filters');
var builtin_loaders = require('./loaders');
var builtin_tests = require('./tests');
var runtime = require('./runtime');
var globals = require('./globals');
var waterfall = require('a-sync-waterfall');
var Frame = runtime.Frame;
var Template;
// If the user is using the async API, *always* call it
// asynchronously even if the template was synchronous.
function callbackAsap(cb, err, res) {
asap(function() {
cb(err, res);
});
}
var Environment = Obj.extend({
init: function(loaders, opts) {
// The dev flag determines the trace that'll be shown on errors.
// If set to true, returns the full trace from the error point,
// otherwise will return trace starting from Template.render
// (the full trace from within nunjucks may confuse developers using
// the library)
// defaults to false
opts = this.opts = opts || {};
this.opts.dev = !!opts.dev;
// The autoescape flag sets global autoescaping. If true,
// every string variable will be escaped by default.
// If false, strings can be manually escaped using the `escape` filter.
// defaults to true
this.opts.autoescape = opts.autoescape != null ? opts.autoescape : true;
// If true, this will make the system throw errors if trying
// to output a null or undefined value
this.opts.throwOnUndefined = !!opts.throwOnUndefined;
this.opts.trimBlocks = !!opts.trimBlocks;
this.opts.lstripBlocks = !!opts.lstripBlocks;
this.loaders = [];
if (!loaders) {
// The filesystem loader is only available server-side
if (builtin_loaders.FileSystemLoader) {
this.loaders = [new builtin_loaders.FileSystemLoader('views')];
} else if (builtin_loaders.WebLoader) {
this.loaders = [new builtin_loaders.WebLoader('/views')];
}
} else {
this.loaders = lib.isArray(loaders) ? loaders : [loaders];
}
// It's easy to use precompiled templates: just include them
// before you configure nunjucks and this will automatically
// pick it up and use it
if (typeof window !== 'undefined' && window.nunjucksPrecompiled) {
this.loaders.unshift(
new builtin_loaders.PrecompiledLoader(window.nunjucksPrecompiled)
);
}
this.initCache();
this.globals = globals();
this.filters = {};
this.tests = {};
this.asyncFilters = [];
this.extensions = {};
this.extensionsList = [];
for (var name in builtin_filters) {
this.addFilter(name, builtin_filters[name]);
}
for (var test in builtin_tests) {
this.addTest(test, builtin_tests[test]);
}
},
initCache: function() {
// Caching and cache busting
lib.each(this.loaders, function(loader) {
loader.cache = {};
if (typeof loader.on === 'function') {
loader.on('update', function(template) {
loader.cache[template] = null;
});
}
});
},
addExtension: function(name, extension) {
extension._name = name;
this.extensions[name] = extension;
this.extensionsList.push(extension);
return this;
},
removeExtension: function(name) {
var extension = this.getExtension(name);
if (!extension) {
return;
}
this.extensionsList = lib.without(this.extensionsList, extension);
delete this.extensions[name];
},
getExtension: function(name) {
return this.extensions[name];
},
hasExtension: function(name) {
return !!this.extensions[name];
},
addGlobal: function(name, value) {
this.globals[name] = value;
return this;
},
getGlobal: function(name) {
if (typeof this.globals[name] === 'undefined') {
throw new Error('global not found: ' + name);
}
return this.globals[name];
},
addFilter: function(name, func, async) {
var wrapped = func;
if (async) {
this.asyncFilters.push(name);
}
this.filters[name] = wrapped;
return this;
},
getFilter: function(name) {
if (!this.filters[name]) {
throw new Error('filter not found: ' + name);
}
return this.filters[name];
},
addTest: function(name, func) {
this.tests[name] = func;
return this;
},
getTest: function(name) {
if (!this.tests[name]) {
throw new Error('test not found: ' + name);
}
return this.tests[name];
},
resolveTemplate: function(loader, parentName, filename) {
var isRelative = (loader.isRelative && parentName) ? loader.isRelative(filename) : false;
return (isRelative && loader.resolve) ? loader.resolve(parentName, filename) : filename;
},
getTemplate: function(name, eagerCompile, parentName, ignoreMissing, cb) {
var that = this;
var tmpl = null;
if (name && name.raw) {
// this fixes autoescape for templates referenced in symbols
name = name.raw;
}
if (lib.isFunction(parentName)) {
cb = parentName;
parentName = null;
eagerCompile = eagerCompile || false;
}
if (lib.isFunction(eagerCompile)) {
cb = eagerCompile;
eagerCompile = false;
}
if (name instanceof Template) {
tmpl = name;
} else if (typeof name !== 'string') {
throw new Error('template names must be a string: ' + name);
} else {
for (var i = 0; i < this.loaders.length; i++) {
var _name = this.resolveTemplate(this.loaders[i], parentName, name);
tmpl = this.loaders[i].cache[_name];
if (tmpl) {
break;
}
}
}
if (tmpl) {
if (eagerCompile) {
tmpl.compile();
}
if (cb) {
cb(null, tmpl);
} else {
return tmpl;
}
} else {
var syncResult;
var _this = this;
var createTemplate = function(err, info) {
if (!info && !err) {
if (!ignoreMissing) {
err = new Error('template not found: ' + name);
}
}
if (err) {
if (cb) {
cb(err);
} else {
throw err;
}
} else {
var tmpl;
if (info) {
tmpl = new Template(info.src, _this,
info.path, eagerCompile);
if (!info.noCache) {
info.loader.cache[name] = tmpl;
}
} else {
tmpl = new Template({
type: 'code',
obj: {
root: function root(env, context, frame, runtime, cb) {
try {
cb(null, '');
} catch (e) {
cb(runtime.handleError(e, null, null));
}
}
}
}, _this, '', eagerCompile);
}
if (cb) {
cb(null, tmpl);
} else {
syncResult = tmpl;
}
}
};
lib.asyncIter(this.loaders, function(loader, i, next, done) {
function handle(err, src) {
if (err) {
done(err);
} else if (src) {
src.loader = loader;
done(null, src);
} else {
next();
}
}
// Resolve name relative to parentName
name = that.resolveTemplate(loader, parentName, name);
if (loader.async) {
loader.getSource(name, handle);
} else {
handle(null, loader.getSource(name));
}
}, createTemplate);
return syncResult;
}
},
express: function(app) {
var env = this;
function NunjucksView(name, opts) {
this.name = name;
this.path = name;
this.defaultEngine = opts.defaultEngine;
this.ext = path.extname(name);
if (!this.ext && !this.defaultEngine) {
throw new Error('No default engine was specified and no extension was provided.');
}
if (!this.ext) {
this.name += (this.ext = ('.' !== this.defaultEngine[0] ? '.' : '') + this.defaultEngine);
}
}
NunjucksView.prototype.render = function(opts, cb) {
env.render(this.name, opts, cb);
};
app.set('view', NunjucksView);
app.set('nunjucksEnv', this);
return this;
},
render: function(name, ctx, cb) {
if (lib.isFunction(ctx)) {
cb = ctx;
ctx = null;
}
// We support a synchronous API to make it easier to migrate
// existing code to async. This works because if you don't do
// anything async work, the whole thing is actually run
// synchronously.
var syncResult = null;
this.getTemplate(name, function(err, tmpl) {
if (err && cb) {
callbackAsap(cb, err);
} else if (err) {
throw err;
} else {
syncResult = tmpl.render(ctx, cb);
}
});
return syncResult;
},
renderString: function(src, ctx, opts, cb) {
if (lib.isFunction(opts)) {
cb = opts;
opts = {};
}
opts = opts || {};
var tmpl = new Template(src, this, opts.path);
return tmpl.render(ctx, cb);
},
waterfall: waterfall
});
var Context = Obj.extend({
init: function(ctx, blocks, env) {
// Has to be tied to an environment so we can tap into its globals.
this.env = env || new Environment();
// Make a duplicate of ctx
this.ctx = {};
for (var k in ctx) {
if (Object.prototype.hasOwnProperty.call(ctx, k)) {
this.ctx[k] = ctx[k];
}
}
this.blocks = {};
this.exported = [];
for (var name in blocks) {
this.addBlock(name, blocks[name]);
}
},
lookup: function(name) {
// This is one of the most called functions, so optimize for
// the typical case where the name isn't in the globals
if (name in this.env.globals && !(name in this.ctx)) {
return this.env.globals[name];
} else {
return this.ctx[name];
}
},
setVariable: function(name, val) {
this.ctx[name] = val;
},
getVariables: function() {
return this.ctx;
},
addBlock: function(name, block) {
this.blocks[name] = this.blocks[name] || [];
this.blocks[name].push(block);
return this;
},
getBlock: function(name) {
if (!this.blocks[name]) {
throw new Error('unknown block "' + name + '"');
}
return this.blocks[name][0];
},
getSuper: function(env, name, block, frame, runtime, cb) {
var idx = lib.indexOf(this.blocks[name] || [], block);
var blk = this.blocks[name][idx + 1];
var context = this;
if (idx === -1 || !blk) {
throw new Error('no super block available for "' + name + '"');
}
blk(env, context, frame, runtime, cb);
},
addExport: function(name) {
this.exported.push(name);
},
getExported: function() {
var exported = {};
for (var i = 0; i < this.exported.length; i++) {
var name = this.exported[i];
exported[name] = this.ctx[name];
}
return exported;
}
});
Template = Obj.extend({
init: function(src, env, path, eagerCompile) {
this.env = env || new Environment();
if (lib.isObject(src)) {
switch (src.type) {
case 'code':
this.tmplProps = src.obj;
break;
case 'string':
this.tmplStr = src.obj;
break;
}
} else if (lib.isString(src)) {
this.tmplStr = src;
} else {
throw new Error('src must be a string or an object describing ' +
'the source');
}
this.path = path;
if (eagerCompile) {
var _this = this;
try {
_this._compile();
} catch (err) {
throw lib.prettifyError(this.path, this.env.opts.dev, err);
}
} else {
this.compiled = false;
}
},
render: function(ctx, parentFrame, cb) {
if (typeof ctx === 'function') {
cb = ctx;
ctx = {};
} else if (typeof parentFrame === 'function') {
cb = parentFrame;
parentFrame = null;
}
var forceAsync = true;
if (parentFrame) {
// If there is a frame, we are being called from internal
// code of another template, and the internal system
// depends on the sync/async nature of the parent template
// to be inherited, so force an async callback
forceAsync = false;
}
var _this = this;
// Catch compile errors for async rendering
try {
_this.compile();
} catch (_err) {
var err = lib.prettifyError(this.path, this.env.opts.dev, _err);
if (cb) {
return callbackAsap(cb, err);
} else {
throw err;
}
}
var context = new Context(ctx || {}, _this.blocks, _this.env);
var frame = parentFrame ? parentFrame.push(true) : new Frame();
frame.topLevel = true;
var syncResult = null;
var didError = false;
_this.rootRenderFunc(
_this.env,
context,
frame || new Frame(),
runtime,
function(err, res) {
if (didError) {
// prevent multiple calls to cb
return;
}
if (err) {
err = lib.prettifyError(_this.path, _this.env.opts.dev, err);
didError = true;
}
if (cb) {
if (forceAsync) {
callbackAsap(cb, err, res);
} else {
cb(err, res);
}
} else {
if (err) {
throw err;
}
syncResult = res;
}
}
);
return syncResult;
},
getExported: function(ctx, parentFrame, cb) {
if (typeof ctx === 'function') {
cb = ctx;
ctx = {};
}
if (typeof parentFrame === 'function') {
cb = parentFrame;
parentFrame = null;
}
// Catch compile errors for async rendering
try {
this.compile();
} catch (e) {
if (cb) {
return cb(e);
} else {
throw e;
}
}
var frame = parentFrame ? parentFrame.push() : new Frame();
frame.topLevel = true;
// Run the rootRenderFunc to populate the context with exported vars
var context = new Context(ctx || {}, this.blocks, this.env);
this.rootRenderFunc(this.env,
context,
frame,
runtime,
function(err) {
if (err) {
cb(err, null);
} else {
cb(null, context.getExported());
}
});
},
compile: function() {
if (!this.compiled) {
this._compile();
}
},
_compile: function() {
var props;
if (this.tmplProps) {
props = this.tmplProps;
} else {
var source = compiler.compile(this.tmplStr,
this.env.asyncFilters,
this.env.extensionsList,
this.path,
this.env.opts);
/* jslint evil: true */
var func = new Function(source);
props = func();
}
this.blocks = this._getBlocks(props);
this.rootRenderFunc = props.root;
this.compiled = true;
},
_getBlocks: function(props) {
var blocks = {};
for (var k in props) {
if (k.slice(0, 2) === 'b_') {
blocks[k.slice(2)] = props[k];
}
}
return blocks;
}
});
module.exports = {
Environment: Environment,
Template: Template
};