-
Notifications
You must be signed in to change notification settings - Fork 479
/
Copy pathdust-core.js
1214 lines (1090 loc) · 34.1 KB
/
dust-core.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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*! dustjs-linkedin - v3.0.0
* http://dustjs.com/
* Copyright (c) 2021 Aleksander Williams; Released under the MIT License */
(function (root, factory) {
if (typeof define === 'function' && define.amd && define.amd.dust === true) {
define('dust.core', [], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.dust = factory();
}
}(this, function() {
var dust = {
"version": "3.0.0"
},
NONE = 'NONE', ERROR = 'ERROR', WARN = 'WARN', INFO = 'INFO', DEBUG = 'DEBUG',
EMPTY_FUNC = function() {};
dust.config = {
whitespace: false,
amd: false,
cjs: false,
cache: true
};
// Directive aliases to minify code
dust._aliases = {
"write": "w",
"end": "e",
"map": "m",
"render": "r",
"reference": "f",
"section": "s",
"exists": "x",
"notexists": "nx",
"block": "b",
"partial": "p",
"helper": "h"
};
(function initLogging() {
/*global process, console*/
var loggingLevels = { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, NONE: 4 },
consoleLog,
log;
if (typeof console !== 'undefined' && console.log) {
consoleLog = console.log;
if(typeof consoleLog === 'function') {
log = function() {
consoleLog.apply(console, arguments);
};
} else {
log = function() {
consoleLog(Array.prototype.slice.apply(arguments).join(' '));
};
}
} else {
log = EMPTY_FUNC;
}
/**
* Filters messages based on `dust.debugLevel`.
* This default implementation will print to the console if it exists.
* @param {String|Error} message the message to print/throw
* @param {String} type the severity of the message(ERROR, WARN, INFO, or DEBUG)
* @public
*/
dust.log = function(message, type) {
type = type || INFO;
if (loggingLevels[type] >= loggingLevels[dust.debugLevel]) {
log('[DUST:' + type + ']', message);
if (type === ERROR && dust.debugLevel === DEBUG && message instanceof Error && message.stack) {
log('[DUST:' + type + ']', message.stack);
}
}
};
dust.debugLevel = NONE;
if(typeof process !== 'undefined' && process.env && /\bdust\b/.test(process.env.DEBUG)) {
dust.debugLevel = DEBUG;
}
}());
dust.helpers = {};
dust.cache = {};
dust.register = function(name, tmpl) {
if (!name) {
return;
}
tmpl.templateName = name;
if (dust.config.cache !== false) {
dust.cache[name] = tmpl;
}
};
dust.render = function(nameOrTemplate, context, callback) {
var chunk = new Stub(callback).head;
try {
load(nameOrTemplate, chunk, context).end();
} catch (err) {
chunk.setError(err);
}
};
dust.stream = function(nameOrTemplate, context) {
var stream = new Stream(),
chunk = stream.head;
dust.nextTick(function() {
try {
load(nameOrTemplate, chunk, context).end();
} catch (err) {
chunk.setError(err);
}
});
return stream;
};
/**
* Extracts a template function (body_0) from whatever is passed.
* @param nameOrTemplate {*} Could be:
* - the name of a template to load from cache
* - a CommonJS-compiled template (a function with a `template` property)
* - a template function
* @param loadFromCache {Boolean} if false, don't look in the cache
* @return {Function} a template function, if found
*/
function getTemplate(nameOrTemplate, loadFromCache/*=true*/) {
if(!nameOrTemplate) {
return;
}
if(typeof nameOrTemplate === 'function' && nameOrTemplate.template) {
// Sugar away CommonJS module templates
return nameOrTemplate.template;
}
if(dust.isTemplateFn(nameOrTemplate)) {
// Template functions passed directly
return nameOrTemplate;
}
if(loadFromCache !== false) {
// Try loading a template with this name from cache
return dust.cache[nameOrTemplate];
}
}
function load(nameOrTemplate, chunk, context) {
if(!nameOrTemplate) {
return chunk.setError(new Error('No template or template name provided to render'));
}
var template = getTemplate(nameOrTemplate, dust.config.cache);
if (template) {
return template(chunk, Context.wrap(context, template.templateName));
} else {
if (dust.onLoad) {
return chunk.map(function(chunk) {
// Alias just so it's easier to read that this would always be a name
var name = nameOrTemplate;
// Three possible scenarios for a successful callback:
// - `require(nameOrTemplate)(dust); cb()`
// - `src = readFile('src.dust'); cb(null, src)`
// - `compiledTemplate = require(nameOrTemplate)(dust); cb(null, compiledTemplate)`
function done(err, srcOrTemplate) {
var template;
if (err) {
return chunk.setError(err);
}
// Prefer a template that is passed via callback over the cached version.
template = getTemplate(srcOrTemplate, false) || getTemplate(name, dust.config.cache);
if (!template) {
// It's a template string, compile it and register under `name`
if(dust.compile) {
template = dust.loadSource(dust.compile(srcOrTemplate, name));
} else {
return chunk.setError(new Error('Dust compiler not available'));
}
}
template(chunk, Context.wrap(context, template.templateName)).end();
}
if(dust.onLoad.length === 3) {
dust.onLoad(name, context.options, done);
} else {
dust.onLoad(name, done);
}
});
}
return chunk.setError(new Error('Template Not Found: ' + nameOrTemplate));
}
}
dust.loadSource = function(source) {
/*jshint evil:true*/
return eval(source);
};
if (Array.isArray) {
dust.isArray = Array.isArray;
} else {
dust.isArray = function(arr) {
return Object.prototype.toString.call(arr) === '[object Array]';
};
}
dust.nextTick = (function() {
return function(callback) {
setTimeout(callback, 0);
};
})();
/**
* Dust has its own rules for what is "empty"-- which is not the same as falsy.
* Empty arrays, null, and undefined are empty
*/
dust.isEmpty = function(value) {
if (value === 0) {
return false;
}
if (dust.isArray(value) && !value.length) {
return true;
}
return !value;
};
dust.isEmptyObject = function(obj) {
var key;
if (obj === null) {
return false;
}
if (obj === undefined) {
return false;
}
if (obj.length > 0) {
return false;
}
for (key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
};
dust.isTemplateFn = function(elem) {
return typeof elem === 'function' &&
elem.__dustBody;
};
/**
* Decide somewhat-naively if something is a Thenable. Matches Promises A+ Spec, section 1.2 “thenable” is an object or function that defines a then method."
* @param elem {*} object to inspect
* @return {Boolean} is `elem` a Thenable?
*/
dust.isThenable = function(elem) {
return elem && /* Beware: `typeof null` is `object` */
(typeof elem === 'object' || typeof elem === 'function') &&
typeof elem.then === 'function';
};
/**
* Decide if an element is a function but not Thenable; it is prefereable to resolve a thenable function by its `.then` method.
* @param elem {*} target of inspection
* @return {Boolean} is `elem` a function without a `.then` property?
*/
dust.isNonThenableFunction = function(elem) {
return typeof elem === 'function' && !dust.isThenable(elem);
};
/**
* Decide very naively if something is a Stream.
* @param elem {*} object to inspect
* @return {Boolean} is `elem` a Stream?
*/
dust.isStreamable = function(elem) {
return elem &&
typeof elem.on === 'function' &&
typeof elem.pipe === 'function';
};
// apply the filter chain and return the output string
dust.filter = function(string, auto, filters, context) {
var i, len, name, filter;
if (filters) {
for (i = 0, len = filters.length; i < len; i++) {
name = filters[i];
if (!name.length) {
continue;
}
filter = dust.filters[name];
if (name === 's') {
auto = null;
} else if (typeof filter === 'function') {
string = filter(string, context);
} else {
dust.log('Invalid filter `' + name + '`', WARN);
}
}
}
// by default always apply the h filter, unless asked to unescape with |s
if (auto) {
string = dust.filters[auto](string, context);
}
return string;
};
dust.filters = {
h: function(value) { return dust.escapeHtml(value); },
j: function(value) { return dust.escapeJs(value); },
u: encodeURI,
uc: encodeURIComponent,
js: function(value) { return dust.escapeJSON(value); },
jp: function(value) {
if (!JSON) {dust.log('JSON is undefined; could not parse `' + value + '`', WARN);
return value;
} else {
return JSON.parse(value);
}
}
};
function Context(stack, global, options, blocks, templateName) {
if(stack !== undefined && !(stack instanceof Stack)) {
stack = new Stack(stack);
}
this.stack = stack;
this.global = global;
this.options = options;
this.blocks = blocks;
this.templateName = templateName;
this._isContext = true;
}
dust.makeBase = dust.context = function(global, options) {
return new Context(undefined, global, options);
};
dust.isContext = function(obj) {
return typeof obj === "object" && obj._isContext === true;
};
/**
* Factory function that creates a closure scope around a Thenable-callback.
* Returns a function that can be passed to a Thenable that will resume a
* Context lookup once the Thenable resolves with new data, adding that new
* data to the lookup stack.
*/
function getWithResolvedData(ctx, cur, down) {
return function(data) {
return ctx.push(data)._get(cur, down);
};
}
Context.wrap = function(context, name) {
if (dust.isContext(context)) {
context.templateName = name;
return context;
}
return new Context(context, {}, {}, null, name);
};
/**
* Public API for getting a value from the context.
* @method get
* @param {string|array} path The path to the value. Supported formats are:
* 'key'
* 'path.to.key'
* '.path.to.key'
* ['path', 'to', 'key']
* ['key']
* @param {boolean} [cur=false] Boolean which determines if the search should be limited to the
* current context (true), or if get should search in parent contexts as well (false).
* @public
* @returns {string|object}
*/
Context.prototype.get = function(path, cur) {
if (typeof path === 'string') {
if (path[0] === '.') {
cur = true;
path = path.substr(1);
}
path = path.split('.');
}
return this._get(cur, path);
};
/**
* Get a value from the context
* @method _get
* @param {boolean} cur Get only from the current context
* @param {array} down An array of each step in the path
* @private
* @return {string | object}
*/
Context.prototype._get = function(cur, down) {
var ctx = this.stack || {},
i = 1,
value, first, len, ctxThis, fn;
first = down[0];
len = down.length;
if (cur && len === 0) {
ctxThis = ctx;
ctx = ctx.head;
} else {
if (!cur) {
// Search up the stack for the first value
while (ctx) {
if (ctx.isObject) {
ctxThis = ctx.head;
value = ctx.head[first];
if (value !== undefined) {
break;
}
}
ctx = ctx.tail;
}
// Try looking in the global context if we haven't found anything yet
if (value !== undefined) {
ctx = value;
} else {
ctx = this.global && this.global[first];
}
} else if (ctx) {
// if scope is limited by a leading dot, don't search up the tree
if(ctx.head) {
ctx = ctx.head[first];
} else {
// context's head is empty, value we are searching for is not defined
ctx = undefined;
}
}
while (ctx && i < len) {
if (dust.isThenable(ctx)) {
// Bail early by returning a Thenable for the remainder of the search tree
return ctx.then(getWithResolvedData(this, cur, down.slice(i)));
}
ctxThis = ctx;
ctx = ctx[down[i]];
i++;
}
}
if (dust.isNonThenableFunction(ctx)) {
fn = function() {
try {
return ctx.apply(ctxThis, arguments);
} catch (err) {
dust.log(err, ERROR);
throw err;
}
};
fn.__dustBody = !!ctx.__dustBody;
return fn;
} else {
if (ctx === undefined) {
dust.log('Cannot find reference `{' + down.join('.') + '}` in template `' + this.getTemplateName() + '`', INFO);
}
return ctx;
}
};
Context.prototype.getPath = function(cur, down) {
return this._get(cur, down);
};
Context.prototype.push = function(head, idx, len) {
if(head === undefined) {
dust.log("Not pushing an undefined variable onto the context", INFO);
return this;
}
return this.rebase(new Stack(head, this.stack, idx, len));
};
Context.prototype.pop = function() {
var head = this.current();
this.stack = this.stack && this.stack.tail;
return head;
};
Context.prototype.rebase = function(head) {
return new Context(head, this.global, this.options, this.blocks, this.getTemplateName());
};
Context.prototype.clone = function() {
var context = this.rebase();
context.stack = this.stack;
return context;
};
Context.prototype.current = function() {
return this.stack && this.stack.head;
};
Context.prototype.getBlock = function(key) {
var blocks, len, fn;
if (typeof key === 'function') {
key = key(new Chunk(), this).data.join('');
}
blocks = this.blocks;
if (!blocks) {
dust.log('No blocks for context `' + key + '` in template `' + this.getTemplateName() + '`', DEBUG);
return false;
}
len = blocks.length;
while (len--) {
fn = blocks[len][key];
if (fn) {
return fn;
}
}
dust.log('Malformed template `' + this.getTemplateName() + '` was missing one or more blocks.');
return false;
};
Context.prototype.shiftBlocks = function(locals) {
var blocks = this.blocks,
newBlocks;
if (locals) {
if (!blocks) {
newBlocks = [locals];
} else {
newBlocks = blocks.concat([locals]);
}
return new Context(this.stack, this.global, this.options, newBlocks, this.getTemplateName());
}
return this;
};
Context.prototype.resolve = function(body) {
var chunk;
if(typeof body !== 'function') {
return body;
}
chunk = new Chunk().render(body, this);
if(chunk instanceof Chunk) {
return chunk.data.join(''); // ie7 perf
}
return chunk;
};
Context.prototype.getTemplateName = function() {
return this.templateName;
};
function Stack(head, tail, idx, len) {
this.tail = tail;
this.isObject = head && typeof head === 'object';
this.head = head;
this.index = idx;
this.of = len;
}
function Stub(callback) {
this.head = new Chunk(this);
this.callback = callback;
this.out = '';
}
Stub.prototype.flush = function() {
var chunk = this.head;
while (chunk) {
if (chunk.flushable) {
this.out += chunk.data.join(''); //ie7 perf
} else if (chunk.error) {
this.callback(chunk.error);
dust.log('Rendering failed with error `' + chunk.error + '`', ERROR);
this.flush = EMPTY_FUNC;
return;
} else {
return;
}
chunk = chunk.next;
this.head = chunk;
}
this.callback(null, this.out);
};
/**
* Creates an interface sort of like a Streams2 ReadableStream.
*/
function Stream() {
this.head = new Chunk(this);
}
Stream.prototype.flush = function() {
var chunk = this.head;
while(chunk) {
if (chunk.flushable) {
this.emit('data', chunk.data.join('')); //ie7 perf
} else if (chunk.error) {
this.emit('error', chunk.error);
this.emit('end');
dust.log('Streaming failed with error `' + chunk.error + '`', ERROR);
this.flush = EMPTY_FUNC;
return;
} else {
return;
}
chunk = chunk.next;
this.head = chunk;
}
this.emit('end');
};
/**
* Executes listeners for `type` by passing data. Note that this is different from a
* Node stream, which can pass an arbitrary number of arguments
* @return `true` if event had listeners, `false` otherwise
*/
Stream.prototype.emit = function(type, data) {
var events = this.events || {},
handlers = events[type] || [],
i, l;
if (!handlers.length) {
dust.log('Stream broadcasting, but no listeners for `' + type + '`', DEBUG);
return false;
}
handlers = handlers.slice(0);
for (i = 0, l = handlers.length; i < l; i++) {
handlers[i](data);
}
return true;
};
Stream.prototype.on = function(type, callback) {
var events = this.events = this.events || {},
handlers = events[type] = events[type] || [];
if(typeof callback !== 'function') {
dust.log('No callback function provided for `' + type + '` event listener', WARN);
} else {
handlers.push(callback);
}
return this;
};
/**
* Pipes to a WritableStream. Note that backpressure isn't implemented,
* so we just write as fast as we can.
* @param stream {WritableStream}
* @return self
*/
Stream.prototype.pipe = function(stream) {
if(typeof stream.write !== 'function' ||
typeof stream.end !== 'function') {
dust.log('Incompatible stream passed to `pipe`', WARN);
return this;
}
var destEnded = false;
if(typeof stream.emit === 'function') {
stream.emit('pipe', this);
}
if(typeof stream.on === 'function') {
stream.on('error', function() {
destEnded = true;
});
}
return this
.on('data', function(data) {
if(destEnded) {
return;
}
try {
stream.write(data, 'utf8');
} catch (err) {
dust.log(err, ERROR);
}
})
.on('end', function() {
if(destEnded) {
return;
}
try {
stream.end();
destEnded = true;
} catch (err) {
dust.log(err, ERROR);
}
});
};
function Chunk(root, next, taps) {
this.root = root;
this.next = next;
this.data = []; //ie7 perf
this.flushable = false;
this.taps = taps;
}
Chunk.prototype.write = function(data) {
var taps = this.taps;
if (taps) {
data = taps.go(data);
}
this.data.push(data);
return this;
};
Chunk.prototype.end = function(data) {
if (data) {
this.write(data);
}
this.flushable = true;
this.root.flush();
return this;
};
/**
* Inserts a new chunk that can be used to asynchronously render or write to it
* @param callback {Function} The function that will be called with the new chunk
* @returns {Chunk} A copy of this chunk instance in order to further chain function calls on the chunk
*/
Chunk.prototype.map = function(callback) {
var cursor = new Chunk(this.root, this.next, this.taps),
branch = new Chunk(this.root, cursor, this.taps);
this.next = branch;
this.flushable = true;
try {
callback(branch);
} catch(err) {
dust.log(err, ERROR);
branch.setError(err);
}
return cursor;
};
/**
* Like Chunk#map but additionally resolves a thenable. If the thenable succeeds the callback is invoked with
* a new chunk that can be used to asynchronously render or write to it, otherwise if the thenable is rejected
* then the error body is rendered if available, an error is logged, and the callback is never invoked.
* @param {Chunk} The current chunk to insert a new chunk
* @param thenable {Thenable} the target thenable to await
* @param context {Context} context to use to render the deferred chunk
* @param bodies {Object} may optionally contain an "error" for when the thenable is rejected
* @param callback {Function} The function that will be called with the new chunk
* @returns {Chunk} A copy of this chunk instance in order to further chain function calls on the chunk
*/
function mapThenable(chunk, thenable, context, bodies, callback) {
return chunk.map(function(asyncChunk) {
thenable.then(function(data) {
try {
callback(asyncChunk, data);
} catch (err) {
// handle errors the same way Chunk#map would. This logic is only here since the thenable defers
// logic such that the try / catch in Chunk#map would not capture it.
dust.log(err, ERROR);
asyncChunk.setError(err);
}
}, function(err) {
dust.log('Unhandled promise rejection in `' + context.getTemplateName() + '`', INFO);
asyncChunk.renderError(err, context, bodies).end();
});
});
}
Chunk.prototype.tap = function(tap) {
var taps = this.taps;
if (taps) {
this.taps = taps.push(tap);
} else {
this.taps = new Tap(tap);
}
return this;
};
Chunk.prototype.untap = function() {
this.taps = this.taps.tail;
return this;
};
Chunk.prototype.render = function(body, context) {
return body(this, context);
};
Chunk.prototype.reference = function(elem, context, auto, filters) {
if (dust.isNonThenableFunction(elem)) {
elem = elem.apply(context.current(), [this, context, null, {auto: auto, filters: filters}]);
if (elem instanceof Chunk) {
return elem;
} else {
return this.reference(elem, context, auto, filters);
}
}
if (dust.isThenable(elem)) {
return this.await(elem, context, null, auto, filters);
} else if (dust.isStreamable(elem)) {
return this.stream(elem, context, null, auto, filters);
} else if (!dust.isEmpty(elem)) {
return this.write(dust.filter(elem, auto, filters, context));
} else {
return this;
}
};
Chunk.prototype.section = function(elem, context, bodies, params) {
var body = bodies.block,
skip = bodies['else'],
chunk = this,
i, len, head;
if (dust.isNonThenableFunction(elem) && !dust.isTemplateFn(elem)) {
try {
elem = elem.apply(context.current(), [this, context, bodies, params]);
} catch(err) {
dust.log(err, ERROR);
return this.setError(err);
}
// Functions that return chunks are assumed to have handled the chunk manually.
// Make that chunk the current one and go to the next method in the chain.
if (elem instanceof Chunk) {
return elem;
}
}
if (dust.isEmptyObject(bodies)) {
// No bodies to render, and we've already invoked any function that was available in
// hopes of returning a Chunk.
return chunk;
}
if (!dust.isEmptyObject(params)) {
context = context.push(params);
}
/*
Dust's default behavior is to enumerate over the array elem, passing each object in the array to the block.
When elem resolves to a value or object instead of an array, Dust sets the current context to the value
and renders the block one time.
*/
if (dust.isArray(elem)) {
if (body) {
len = elem.length;
if (len > 0) {
head = context.stack && context.stack.head || {};
head.$len = len;
for (i = 0; i < len; i++) {
head.$idx = i;
chunk = body(chunk, context.push(elem[i], i, len));
}
head.$idx = undefined;
head.$len = undefined;
return chunk;
} else if (skip) {
return skip(this, context);
}
}
} else if (dust.isThenable(elem)) {
return this.await(elem, context, bodies);
} else if (dust.isStreamable(elem)) {
return this.stream(elem, context, bodies);
} else if (elem === true) {
// true is truthy but does not change context
if (body) {
return body(this, context);
}
} else if (elem || elem === 0) {
// everything that evaluates to true are truthy ( e.g. Non-empty strings and Empty objects are truthy. )
// zero is truthy
// for anonymous functions that did not returns a chunk, truthiness is evaluated based on the return value
if (body) {
return body(this, context.push(elem));
}
// nonexistent, scalar false value, scalar empty string, null,
// undefined are all falsy
} else if (skip) {
return skip(this, context);
}
dust.log('Section without corresponding key in template `' + context.getTemplateName() + '`', DEBUG);
return this;
};
Chunk.prototype.exists = function(elem, context, bodies) {
var body = bodies.block,
skip = bodies['else'];
if (dust.isThenable(elem)) {
return mapThenable(this, elem, context, bodies, function(chunk, data) {
chunk.exists(data, context, bodies).end();
});
}
if (!dust.isEmpty(elem)) {
if (body) {
return body(this, context);
}
dust.log('No block for exists check in template `' + context.getTemplateName() + '`', DEBUG);
} else if (skip) {
return skip(this, context);
}
return this;
};
Chunk.prototype.notexists = function(elem, context, bodies) {
var body = bodies.block,
skip = bodies['else'];
if (dust.isThenable(elem)) {
return mapThenable(this, elem, context, bodies, function(chunk, data) {
chunk.notexists(data, context, bodies).end();
});
}
if (dust.isEmpty(elem)) {
if (body) {
return body(this, context);
}
dust.log('No block for not-exists check in template `' + context.getTemplateName() + '`', DEBUG);
} else if (skip) {
return skip(this, context);
}
return this;
};
Chunk.prototype.block = function(elem, context, bodies) {
var body = elem || bodies.block;
if (body) {
return body(this, context);
}
return this;
};
Chunk.prototype.partial = function(elem, context, partialContext, params) {
var head;
if(params === undefined) {
// Compatibility for < 2.7.0 where `partialContext` did not exist
params = partialContext;
partialContext = context;
}
if (!dust.isEmptyObject(params)) {
partialContext = partialContext.clone();
head = partialContext.pop();
partialContext = partialContext.push(params)
.push(head);
}
if (dust.isTemplateFn(elem)) {
// The eventual result of evaluating `elem` is a partial name
// Load the partial after getting its name and end the async chunk
return this.capture(elem, context, function(name, chunk) {
load(name, chunk, partialContext).end();
});
} else {
return load(elem, this, partialContext);
}
};
Chunk.prototype.helper = function(name, context, bodies, params, auto) {
var chunk = this,
filters = params.filters,
ret;
// Pre-2.7.1 compat: if auto is undefined, it's an old template. Automatically escape
if (auto === undefined) {
auto = 'h';
}
// handle invalid helpers, similar to invalid filters
if(dust.helpers[name]) {
try {
ret = dust.helpers[name](chunk, context, bodies, params);
if (ret instanceof Chunk) {
return ret;
}
if(typeof filters === 'string') {
filters = filters.split('|');
}
if (!dust.isEmptyObject(bodies)) {
return chunk.section(ret, context, bodies, params);
}
// Helpers act slightly differently from functions in context in that they will act as
// a reference if they are self-closing (due to grammar limitations)
// In the Chunk.await function we check to make sure bodies is null before acting as a reference