Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
// The MIT License
2
//
3
// Copyright (c) 2009 Chris Wanstrath (Ruby)
4
// Copyright (c) 2010-2014 Jan Lehnardt (JavaScript)
5
// Copyright (c) 2010-2015 The mustache.js community
6
//
7
// Permission is hereby granted, free of charge, to any person obtaining
8
// a copy of this software and associated documentation files (the
9
// "Software"), to deal in the Software without restriction, including
10
// without limitation the rights to use, copy, modify, merge, publish,
11
// distribute, sublicense, and/or sell copies of the Software, and to
12
// permit persons to whom the Software is furnished to do so, subject to
13
// the following conditions:
14
//
15
// The above copyright notice and this permission notice shall be
16
// included in all copies or substantial portions of the Software.
17
//
18
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25
//
26
 
27
// Description of import into Moodle:
28
// Checkout from https://github.com/moodle/custom-mustache.js Branch: LAMBDA_ARGS (see note below)
29
// Rebase onto latest release tag from https://github.com/janl/mustache.js
30
// Copy mustache.js into lib/amd/src/ in Moodle folder.
31
// Add the license as a comment to the file and these instructions.
32
// Make sure that you have not removed the custom code for '$' and '<'.
33
// Run unit tests.
34
// NOTE:
35
// Check if pull request from branch lambdaUpgrade420 has been accepted
36
// by moodle/custom-mustache.js repo. If not, create one and use lambdaUpgrade420
37
// as your branch in place of LAMBDA_ARGS.
38
 
39
/*!
40
 * mustache.js - Logic-less {{mustache}} templates with JavaScript
41
 * http://github.com/janl/mustache.js
42
 */
43
 
44
var objectToString = Object.prototype.toString;
45
var isArray = Array.isArray || function isArrayPolyfill (object) {
46
  return objectToString.call(object) === '[object Array]';
47
};
48
 
49
function isFunction (object) {
50
  return typeof object === 'function';
51
}
52
 
53
/**
54
 * More correct typeof string handling array
55
 * which normally returns typeof 'object'
56
 */
57
function typeStr (obj) {
58
  return isArray(obj) ? 'array' : typeof obj;
59
}
60
 
61
function escapeRegExp (string) {
62
  return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
63
}
64
 
65
/**
66
 * Null safe way of checking whether or not an object,
67
 * including its prototype, has a given property
68
 */
69
function hasProperty (obj, propName) {
70
  return obj != null && typeof obj === 'object' && (propName in obj);
71
}
72
 
73
/**
74
 * Safe way of detecting whether or not the given thing is a primitive and
75
 * whether it has the given property
76
 */
77
function primitiveHasOwnProperty (primitive, propName) {
78
  return (
79
    primitive != null
80
    && typeof primitive !== 'object'
81
    && primitive.hasOwnProperty
82
    && primitive.hasOwnProperty(propName)
83
  );
84
}
85
 
86
// Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
87
// See https://github.com/janl/mustache.js/issues/189
88
var regExpTest = RegExp.prototype.test;
89
function testRegExp (re, string) {
90
  return regExpTest.call(re, string);
91
}
92
 
93
var nonSpaceRe = /\S/;
94
function isWhitespace (string) {
95
  return !testRegExp(nonSpaceRe, string);
96
}
97
 
98
var entityMap = {
99
  '&': '&amp;',
100
  '<': '&lt;',
101
  '>': '&gt;',
102
  '"': '&quot;',
103
  "'": '&#39;',
104
  '/': '&#x2F;',
105
  '`': '&#x60;',
106
  '=': '&#x3D;'
107
};
108
 
109
function escapeHtml (string) {
110
  return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) {
111
    return entityMap[s];
112
  });
113
}
114
 
115
var whiteRe = /\s*/;
116
var spaceRe = /\s+/;
117
var equalsRe = /\s*=/;
118
var curlyRe = /\s*\}/;
119
var tagRe = /#|\^|\/|>|\{|&|=|!|\$|</;
120
 
121
/**
122
 * Breaks up the given `template` string into a tree of tokens. If the `tags`
123
 * argument is given here it must be an array with two string values: the
124
 * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
125
 * course, the default is to use mustaches (i.e. mustache.tags).
126
 *
127
 * A token is an array with at least 4 elements. The first element is the
128
 * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
129
 * did not contain a symbol (i.e. {{myValue}}) this element is "name". For
130
 * all text that appears outside a symbol this element is "text".
131
 *
132
 * The second element of a token is its "value". For mustache tags this is
133
 * whatever else was inside the tag besides the opening symbol. For text tokens
134
 * this is the text itself.
135
 *
136
 * The third and fourth elements of the token are the start and end indices,
137
 * respectively, of the token in the original template.
138
 *
139
 * Tokens that are the root node of a subtree contain two more elements: 1) an
140
 * array of tokens in the subtree and 2) the index in the original template at
141
 * which the closing tag for that section begins.
142
 *
143
 * Tokens for partials also contain two more elements: 1) a string value of
144
 * indendation prior to that tag and 2) the index of that tag on that line -
145
 * eg a value of 2 indicates the partial is the third tag on this line.
146
 */
147
function parseTemplate (template, tags) {
148
  if (!template)
149
    return [];
150
  var lineHasNonSpace = false;
151
  var sections = [];     // Stack to hold section tokens
152
  var tokens = [];       // Buffer to hold the tokens
153
  var spaces = [];       // Indices of whitespace tokens on the current line
154
  var hasTag = false;    // Is there a {{tag}} on the current line?
155
  var nonSpace = false;  // Is there a non-space char on the current line?
156
  var indentation = '';  // Tracks indentation for tags that use it
157
  var tagIndex = 0;      // Stores a count of number of tags encountered on a line
158
 
159
  // Strips all whitespace tokens array for the current line
160
  // if there was a {{#tag}} on it and otherwise only space.
161
  function stripSpace () {
162
    if (hasTag && !nonSpace) {
163
      while (spaces.length)
164
        delete tokens[spaces.pop()];
165
    } else {
166
      spaces = [];
167
    }
168
 
169
    hasTag = false;
170
    nonSpace = false;
171
  }
172
 
173
  var openingTagRe, closingTagRe, closingCurlyRe;
174
  function compileTags (tagsToCompile) {
175
    if (typeof tagsToCompile === 'string')
176
      tagsToCompile = tagsToCompile.split(spaceRe, 2);
177
 
178
    if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
179
      throw new Error('Invalid tags: ' + tagsToCompile);
180
 
181
    openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
182
    closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
183
    closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1]));
184
  }
185
 
186
  compileTags(tags || mustache.tags);
187
 
188
  var scanner = new Scanner(template);
189
 
190
  var start, type, value, chr, token, openSection, tagName, endTagName;
191
  while (!scanner.eos()) {
192
    start = scanner.pos;
193
 
194
    // Match any text between tags.
195
    value = scanner.scanUntil(openingTagRe);
196
 
197
    if (value) {
198
      for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
199
        chr = value.charAt(i);
200
 
201
        if (isWhitespace(chr)) {
202
          spaces.push(tokens.length);
203
          indentation += chr;
204
        } else {
205
          nonSpace = true;
206
          lineHasNonSpace = true;
207
          indentation += ' ';
208
        }
209
 
210
        tokens.push([ 'text', chr, start, start + 1 ]);
211
        start += 1;
212
 
213
        // Check for whitespace on the current line.
214
        if (chr === '\n') {
215
          stripSpace();
216
          indentation = '';
217
          tagIndex = 0;
218
          lineHasNonSpace = false;
219
        }
220
      }
221
    }
222
 
223
    // Match the opening tag.
224
    if (!scanner.scan(openingTagRe))
225
      break;
226
 
227
    hasTag = true;
228
 
229
    // Get the tag type.
230
    type = scanner.scan(tagRe) || 'name';
231
    scanner.scan(whiteRe);
232
 
233
    // Get the tag value.
234
    if (type === '=') {
235
      value = scanner.scanUntil(equalsRe);
236
      scanner.scan(equalsRe);
237
      scanner.scanUntil(closingTagRe);
238
    } else if (type === '{') {
239
      value = scanner.scanUntil(closingCurlyRe);
240
      scanner.scan(curlyRe);
241
      scanner.scanUntil(closingTagRe);
242
      type = '&';
243
    } else {
244
      value = scanner.scanUntil(closingTagRe);
245
    }
246
 
247
    // Match the closing tag.
248
    if (!scanner.scan(closingTagRe))
249
      throw new Error('Unclosed tag at ' + scanner.pos);
250
 
251
    if (type == '>') {
252
      token = [ type, value, start, scanner.pos, indentation, tagIndex, lineHasNonSpace ];
253
    } else {
254
      token = [ type, value, start, scanner.pos ];
255
    }
256
    tagIndex++;
257
    tokens.push(token);
258
 
259
    if (type === '#' || type === '^' || type === '$' || type === '<') {
260
      sections.push(token);
261
    } else if (type === '/') {
262
      // Check section nesting.
263
      openSection = sections.pop();
264
 
265
      if (!openSection)
266
        throw new Error('Unopened section "' + value + '" at ' + start);
267
      tagName = openSection[1].split(' ', 1)[0];
268
      endTagName = value.split(' ', 1)[0];
269
      if (tagName !== endTagName)
270
        throw new Error('Unclosed section "' + tagName + '" at ' + start);
271
    } else if (type === 'name' || type === '{' || type === '&') {
272
      nonSpace = true;
273
    } else if (type === '=') {
274
      // Set the tags for the next time around.
275
      compileTags(value);
276
    }
277
  }
278
 
279
  stripSpace();
280
 
281
  // Make sure there are no open sections when we're done.
282
  openSection = sections.pop();
283
 
284
  if (openSection)
285
    throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
286
 
287
  return nestTokens(squashTokens(tokens));
288
}
289
 
290
/**
291
 * Combines the values of consecutive text tokens in the given `tokens` array
292
 * to a single token.
293
 */
294
function squashTokens (tokens) {
295
  var squashedTokens = [];
296
 
297
  var token, lastToken;
298
  for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
299
    token = tokens[i];
300
 
301
    if (token) {
302
      if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
303
        lastToken[1] += token[1];
304
        lastToken[3] = token[3];
305
      } else {
306
        squashedTokens.push(token);
307
        lastToken = token;
308
      }
309
    }
310
  }
311
 
312
  return squashedTokens;
313
}
314
 
315
/**
316
 * Forms the given array of `tokens` into a nested tree structure where
317
 * tokens that represent a section have two additional items: 1) an array of
318
 * all tokens that appear in that section and 2) the index in the original
319
 * template that represents the end of that section.
320
 */
321
function nestTokens (tokens) {
322
  var nestedTokens = [];
323
  var collector = nestedTokens;
324
  var sections = [];
325
 
326
  var token, section;
327
  for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
328
    token = tokens[i];
329
 
330
    switch (token[0]) {
331
      case '$':
332
      case '<':
333
      case '#':
334
      case '^':
335
        collector.push(token);
336
        sections.push(token);
337
        collector = token[4] = [];
338
        break;
339
      case '/':
340
        section = sections.pop();
341
        section[5] = token[2];
342
        collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
343
        break;
344
      default:
345
        collector.push(token);
346
    }
347
  }
348
 
349
  return nestedTokens;
350
}
351
 
352
/**
353
 * A simple string scanner that is used by the template parser to find
354
 * tokens in template strings.
355
 */
356
function Scanner (string) {
357
  this.string = string;
358
  this.tail = string;
359
  this.pos = 0;
360
}
361
 
362
/**
363
 * Returns `true` if the tail is empty (end of string).
364
 */
365
Scanner.prototype.eos = function eos () {
366
  return this.tail === '';
367
};
368
 
369
/**
370
 * Tries to match the given regular expression at the current position.
371
 * Returns the matched text if it can match, the empty string otherwise.
372
 */
373
Scanner.prototype.scan = function scan (re) {
374
  var match = this.tail.match(re);
375
 
376
  if (!match || match.index !== 0)
377
    return '';
378
 
379
  var string = match[0];
380
 
381
  this.tail = this.tail.substring(string.length);
382
  this.pos += string.length;
383
 
384
  return string;
385
};
386
 
387
/**
388
 * Skips all text until the given regular expression can be matched. Returns
389
 * the skipped string, which is the entire tail if no match can be made.
390
 */
391
Scanner.prototype.scanUntil = function scanUntil (re) {
392
  var index = this.tail.search(re), match;
393
 
394
  switch (index) {
395
    case -1:
396
      match = this.tail;
397
      this.tail = '';
398
      break;
399
    case 0:
400
      match = '';
401
      break;
402
    default:
403
      match = this.tail.substring(0, index);
404
      this.tail = this.tail.substring(index);
405
  }
406
 
407
  this.pos += match.length;
408
 
409
  return match;
410
};
411
 
412
/**
413
 * Represents a rendering context by wrapping a view object and
414
 * maintaining a reference to the parent context.
415
 */
416
function Context (view, parentContext) {
417
  this.view = view;
418
  this.blocks = {};
419
  this.cache = { '.': this.view };
420
  this.parent = parentContext;
421
}
422
 
423
/**
424
 * Creates a new context using the given view with this context
425
 * as the parent.
426
 */
427
Context.prototype.push = function push (view) {
428
  return new Context(view, this);
429
};
430
 
431
/**
432
 * Set a value in the current block context.
433
 */
434
Context.prototype.setBlockVar = function set (name, value) {
435
  var blocks = this.blocks;
436
  blocks[name] = value;
437
  return value;
438
};
439
/**
440
 * Clear all current block vars.
441
 */
442
Context.prototype.clearBlockVars = function clearBlockVars () {
443
  this.blocks = {};
444
};
445
/**
446
 * Get a value only from the current block context.
447
 */
448
Context.prototype.getBlockVar = function getBlockVar (name) {
449
  var blocks = this.blocks;
450
  var value;
451
  if (blocks.hasOwnProperty(name)) {
452
    value = blocks[name];
453
  } else {
454
    if (this.parent) {
455
      value = this.parent.getBlockVar(name);
456
    }
457
  }
458
  // Can return undefined.
459
  return value;
460
};
461
 
462
/**
463
 * Parse a tag name into an array of name and arguments (space separated, quoted strings allowed).
464
 */
465
Context.prototype.parseNameAndArgs = function parseNameAndArgs (name) {
466
  var parts = name.split(' ');
467
  var inString = false;
468
  var first = true;
469
  var i = 0;
470
  var arg;
471
  var unescapedArg;
472
  var argbuffer;
473
  var finalArgs = [];
474
 
475
  for (i = 0; i < parts.length; i++) {
476
    arg = parts[i];
477
    argbuffer = '';
478
 
479
    if (inString) {
480
      unescapedArg = arg.replace('\\\\', '');
481
      if (unescapedArg.search(/^"$|[^\\]"$/) !== -1) {
482
        finalArgs[finalArgs.length] = argbuffer + ' ' + arg.substr(0, arg.length - 1);
483
        argbuffer = '';
484
        inString = false;
485
      } else {
486
        argbuffer += ' ' + arg;
487
      }
488
    } else {
489
      if (arg.search(/^"/) !== -1 && !first) {
490
        unescapedArg = arg.replace('\\\\', '');
491
        if (unescapedArg.search(/^".*[^\\]"$/) !== -1) {
492
          finalArgs[finalArgs.length] = arg.substr(1, arg.length - 2);
493
        } else {
494
          inString = true;
495
          argbuffer = arg.substr(1);
496
        }
497
      } else {
498
        if (arg.search(/^\d+(\.\d*)?$/) !== -1) {
499
          finalArgs[finalArgs.length] = parseFloat(arg);
500
        } else if (arg === 'true') {
501
          finalArgs[finalArgs.length] = 1;
502
        } else if (arg === 'false') {
503
          finalArgs[finalArgs.length] = 0;
504
        } else if (first) {
505
          finalArgs[finalArgs.length] = arg;
506
        } else {
507
          finalArgs[finalArgs.length] = this.lookup(arg);
508
        }
509
        first = false;
510
      }
511
    }
512
  }
513
 
514
  return finalArgs;
515
};
516
 
517
/**
518
 * Returns the value of the given name in this context, traversing
519
 * up the context hierarchy if the value is absent in this context's view.
520
 */
521
Context.prototype.lookup = function lookup (name) {
522
  var cache = this.cache;
523
  var lambdaArgs = this.parseNameAndArgs(name);
524
  name= lambdaArgs.shift();
525
 
526
  var value;
527
  if (cache.hasOwnProperty(name)) {
528
    value = cache[name];
529
  } else {
530
    var context = this, intermediateValue, names, index, lookupHit = false;
531
 
532
    while (context) {
533
      if (name.indexOf('.') > 0) {
534
        intermediateValue = context.view;
535
        names = name.split('.');
536
        index = 0;
537
 
538
        /**
539
         * Using the dot notion path in `name`, we descend through the
540
         * nested objects.
541
         *
542
         * To be certain that the lookup has been successful, we have to
543
         * check if the last object in the path actually has the property
544
         * we are looking for. We store the result in `lookupHit`.
545
         *
546
         * This is specially necessary for when the value has been set to
547
         * `undefined` and we want to avoid looking up parent contexts.
548
         *
549
         * In the case where dot notation is used, we consider the lookup
550
         * to be successful even if the last "object" in the path is
551
         * not actually an object but a primitive (e.g., a string, or an
552
         * integer), because it is sometimes useful to access a property
553
         * of an autoboxed primitive, such as the length of a string.
554
         **/
555
        while (intermediateValue != null && index < names.length) {
556
          if (index === names.length - 1)
557
            lookupHit = (
558
              hasProperty(intermediateValue, names[index])
559
              || primitiveHasOwnProperty(intermediateValue, names[index])
560
            );
561
 
562
          intermediateValue = intermediateValue[names[index++]];
563
        }
564
      } else {
565
        intermediateValue = context.view[name];
566
 
567
        /**
568
         * Only checking against `hasProperty`, which always returns `false` if
569
         * `context.view` is not an object. Deliberately omitting the check
570
         * against `primitiveHasOwnProperty` if dot notation is not used.
571
         *
572
         * Consider this example:
573
         * ```
574
         * Mustache.render("The length of a football field is {{#length}}{{length}}{{/length}}.", {length: "100 yards"})
575
         * ```
576
         *
577
         * If we were to check also against `primitiveHasOwnProperty`, as we do
578
         * in the dot notation case, then render call would return:
579
         *
580
         * "The length of a football field is 9."
581
         *
582
         * rather than the expected:
583
         *
584
         * "The length of a football field is 100 yards."
585
         **/
586
        lookupHit = hasProperty(context.view, name);
587
      }
588
 
589
      if (lookupHit) {
590
        value = intermediateValue;
591
        break;
592
      }
593
 
594
      context = context.parent;
595
    }
596
 
597
    cache[name] = value;
598
  }
599
 
600
  if (isFunction(value))
601
    value = value.call(this.view, lambdaArgs);
602
 
603
  return value;
604
};
605
 
606
/**
607
 * A Writer knows how to take a stream of tokens and render them to a
608
 * string, given a context. It also maintains a cache of templates to
609
 * avoid the need to parse the same template twice.
610
 */
611
function Writer () {
612
  this.templateCache = {
613
    _cache: {},
614
    set: function set (key, value) {
615
      this._cache[key] = value;
616
    },
617
    get: function get (key) {
618
      return this._cache[key];
619
    },
620
    clear: function clear () {
621
      this._cache = {};
622
    }
623
  };
624
}
625
 
626
/**
627
 * Clears all cached templates in this writer.
628
 */
629
Writer.prototype.clearCache = function clearCache () {
630
  if (typeof this.templateCache !== 'undefined') {
631
    this.templateCache.clear();
632
  }
633
};
634
 
635
/**
636
 * Parses and caches the given `template` according to the given `tags` or
637
 * `mustache.tags` if `tags` is omitted,  and returns the array of tokens
638
 * that is generated from the parse.
639
 */
640
Writer.prototype.parse = function parse (template, tags) {
641
  var cache = this.templateCache;
642
  var cacheKey = template + ':' + (tags || mustache.tags).join(':');
643
  var isCacheEnabled = typeof cache !== 'undefined';
644
  var tokens = isCacheEnabled ? cache.get(cacheKey) : undefined;
645
 
646
  if (tokens == undefined) {
647
    tokens = parseTemplate(template, tags);
648
    isCacheEnabled && cache.set(cacheKey, tokens);
649
  }
650
  return tokens;
651
};
652
 
653
/**
654
 * High-level method that is used to render the given `template` with
655
 * the given `view`.
656
 *
657
 * The optional `partials` argument may be an object that contains the
658
 * names and templates of partials that are used in the template. It may
659
 * also be a function that is used to load partial templates on the fly
660
 * that takes a single argument: the name of the partial.
661
 *
662
 * If the optional `config` argument is given here, then it should be an
663
 * object with a `tags` attribute or an `escape` attribute or both.
664
 * If an array is passed, then it will be interpreted the same way as
665
 * a `tags` attribute on a `config` object.
666
 *
667
 * The `tags` attribute of a `config` object must be an array with two
668
 * string values: the opening and closing tags used in the template (e.g.
669
 * [ "<%", "%>" ]). The default is to mustache.tags.
670
 *
671
 * The `escape` attribute of a `config` object must be a function which
672
 * accepts a string as input and outputs a safely escaped string.
673
 * If an `escape` function is not provided, then an HTML-safe string
674
 * escaping function is used as the default.
675
 */
676
Writer.prototype.render = function render (template, view, partials, config) {
677
  var tags = this.getConfigTags(config);
678
  var tokens = this.parse(template, tags);
679
  var context = (view instanceof Context) ? view : new Context(view, undefined);
680
  return this.renderTokens(tokens, context, partials, template, config);
681
};
682
 
683
/**
684
 * Low-level method that renders the given array of `tokens` using
685
 * the given `context` and `partials`.
686
 *
687
 * Note: The `originalTemplate` is only ever used to extract the portion
688
 * of the original template that was contained in a higher-order section.
689
 * If the template doesn't use higher-order sections, this argument may
690
 * be omitted.
691
 */
692
Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate, config) {
693
  var buffer = '';
694
 
695
  var token, symbol, value;
696
  for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
697
    value = undefined;
698
    token = tokens[i];
699
    symbol = token[0];
700
 
701
    if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate, config);
702
    else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate, config);
703
    else if (symbol === '>') value = this.renderPartial(token, context, partials, config);
704
    else if (symbol === '<') value = this.renderBlock(token, context, partials, originalTemplate, config);
705
    else if (symbol === '$') value = this.renderBlockVariable(token, context, partials, originalTemplate, config);
706
    else if (symbol === '&') value = this.unescapedValue(token, context);
707
    else if (symbol === 'name') value = this.escapedValue(token, context, config);
708
    else if (symbol === 'text') value = this.rawValue(token);
709
 
710
    if (value !== undefined)
711
      buffer += value;
712
  }
713
 
714
  return buffer;
715
};
716
 
717
Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate, config) {
718
  var self = this;
719
  var buffer = '';
720
  var lambdaArgs = context.parseNameAndArgs(token[1]);
721
  var name = lambdaArgs.shift();
722
  var value = context.lookup(name);
723
 
724
  // This function is used to render an arbitrary template
725
  // in the current context by higher-order sections.
726
  function subRender (template) {
727
    return self.render(template, context, partials, config);
728
  }
729
 
730
  if (!value) return;
731
 
732
  if (isArray(value)) {
733
    for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
734
      buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate, config);
735
    }
736
  } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
737
    buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config);
738
  } else if (isFunction(value)) {
739
    if (typeof originalTemplate !== 'string')
740
      throw new Error('Cannot use higher-order sections without the original template');
741
 
742
    // Extract the portion of the original template that the section contains.
743
    value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender, lambdaArgs);
744
 
745
    if (value != null)
746
      buffer += value;
747
  } else {
748
    buffer += this.renderTokens(token[4], context, partials, originalTemplate, config);
749
  }
750
  return buffer;
751
};
752
 
753
Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate, config) {
754
  var value = context.lookup(token[1]);
755
 
756
  // Use JavaScript's definition of falsy. Include empty arrays.
757
  // See https://github.com/janl/mustache.js/issues/186
758
  if (!value || (isArray(value) && value.length === 0))
759
    return this.renderTokens(token[4], context, partials, originalTemplate, config);
760
};
761
 
762
Writer.prototype.indentPartial = function indentPartial (partial, indentation, lineHasNonSpace) {
763
  var filteredIndentation = indentation.replace(/[^ \t]/g, '');
764
  var partialByNl = partial.split('\n');
765
  for (var i = 0; i < partialByNl.length; i++) {
766
    if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) {
767
      partialByNl[i] = filteredIndentation + partialByNl[i];
768
    }
769
  }
770
  return partialByNl.join('\n');
771
};
772
 
773
Writer.prototype.renderPartial = function renderPartial (token, context, partials, config) {
774
  if (!partials) return;
775
  var tags = this.getConfigTags(config);
776
 
777
  var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
778
  if (value != null) {
779
    var lineHasNonSpace = token[6];
780
    var tagIndex = token[5];
781
    var indentation = token[4];
782
    var indentedValue = value;
783
    if (tagIndex == 0 && indentation) {
784
      indentedValue = this.indentPartial(value, indentation, lineHasNonSpace);
785
    }
786
    var tokens = this.parse(indentedValue, tags);
787
    return this.renderTokens(tokens, context, partials, indentedValue, config);
788
  }
789
};
790
 
791
Writer.prototype.renderBlock = function renderBlock (token, context, partials, originalTemplate, config) {
792
  if (!partials) return;
793
 
794
  var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
795
  if (value != null)
796
    // Ignore any wrongly set block vars before we started.
797
    context.clearBlockVars();
798
    // We are only rendering to record the default block variables.
799
    this.renderTokens(token[4], context, partials, originalTemplate, config);
800
    // Now we render and return the result.
801
    var result = this.renderTokens(this.parse(value), context, partials, value, config);
802
    // Don't leak the block variables outside this include.
803
    context.clearBlockVars();
804
    return result;
805
};
806
 
807
Writer.prototype.renderBlockVariable = function renderBlockVariable (token, context, partials, originalTemplate, config) {
808
  var value = token[1];
809
 
810
  var exists = context.getBlockVar(value);
811
  if (!exists) {
812
    context.setBlockVar(value, originalTemplate.slice(token[3], token[5]));
813
    return this.renderTokens(token[4], context, partials, originalTemplate, config);
814
  } else {
815
    return this.renderTokens(this.parse(exists), context, partials, exists, config);
816
  }
817
};
818
 
819
Writer.prototype.unescapedValue = function unescapedValue (token, context) {
820
  var value = context.lookup(token[1]);
821
  if (value != null)
822
    return value;
823
};
824
 
825
Writer.prototype.escapedValue = function escapedValue (token, context, config) {
826
  var escape = this.getConfigEscape(config) || mustache.escape;
827
  var value = context.lookup(token[1]);
828
  if (value != null)
829
    return (typeof value === 'number' && escape === mustache.escape) ? String(value) : escape(value);
830
};
831
 
832
Writer.prototype.rawValue = function rawValue (token) {
833
  return token[1];
834
};
835
 
836
Writer.prototype.getConfigTags = function getConfigTags (config) {
837
  if (isArray(config)) {
838
    return config;
839
  }
840
  else if (config && typeof config === 'object') {
841
    return config.tags;
842
  }
843
  else {
844
    return undefined;
845
  }
846
};
847
 
848
Writer.prototype.getConfigEscape = function getConfigEscape (config) {
849
  if (config && typeof config === 'object' && !isArray(config)) {
850
    return config.escape;
851
  }
852
  else {
853
    return undefined;
854
  }
855
};
856
 
857
var mustache = {
858
  name: 'mustache.js',
859
  version: '4.2.0',
860
  tags: [ '{{', '}}' ],
861
  clearCache: undefined,
862
  escape: undefined,
863
  parse: undefined,
864
  render: undefined,
865
  Scanner: undefined,
866
  Context: undefined,
867
  Writer: undefined,
868
  /**
869
   * Allows a user to override the default caching strategy, by providing an
870
   * object with set, get and clear methods. This can also be used to disable
871
   * the cache by setting it to the literal `undefined`.
872
   */
873
  set templateCache (cache) {
874
    defaultWriter.templateCache = cache;
875
  },
876
  /**
877
   * Gets the default or overridden caching object from the default writer.
878
   */
879
  get templateCache () {
880
    return defaultWriter.templateCache;
881
  }
882
};
883
 
884
// All high-level mustache.* functions use this writer.
885
var defaultWriter = new Writer();
886
 
887
/**
888
 * Clears all cached templates in the default writer.
889
 */
890
mustache.clearCache = function clearCache () {
891
  return defaultWriter.clearCache();
892
};
893
 
894
/**
895
 * Parses and caches the given template in the default writer and returns the
896
 * array of tokens it contains. Doing this ahead of time avoids the need to
897
 * parse templates on the fly as they are rendered.
898
 */
899
mustache.parse = function parse (template, tags) {
900
  return defaultWriter.parse(template, tags);
901
};
902
 
903
/**
904
 * Renders the `template` with the given `view`, `partials`, and `config`
905
 * using the default writer.
906
 */
907
mustache.render = function render (template, view, partials, config) {
908
  if (typeof template !== 'string') {
909
    throw new TypeError('Invalid template! Template should be a "string" ' +
910
                        'but "' + typeStr(template) + '" was given as the first ' +
911
                        'argument for mustache#render(template, view, partials)');
912
  }
913
 
914
  return defaultWriter.render(template, view, partials, config);
915
};
916
 
917
// Export the escaping function so that the user may override it.
918
// See https://github.com/janl/mustache.js/issues/244
919
mustache.escape = escapeHtml;
920
 
921
// Export these mainly for testing, but also for advanced usage.
922
mustache.Scanner = Scanner;
923
mustache.Context = Context;
924
mustache.Writer = Writer;
925
 
926
export default mustache;