|
486 | 486 | * avoid the need to parse the same template twice.
|
487 | 487 | */
|
488 | 488 | function Writer () {
|
489 |
| - this.cache = {}; |
| 489 | + this.templateCache = { |
| 490 | + _cache: {}, |
| 491 | + set: function set (key, value) { |
| 492 | + this._cache[key] = value; |
| 493 | + }, |
| 494 | + get: function get (key) { |
| 495 | + return this._cache[key]; |
| 496 | + }, |
| 497 | + clear: function clear () { |
| 498 | + this._cache = {}; |
| 499 | + } |
| 500 | + }; |
490 | 501 | }
|
491 | 502 |
|
492 | 503 | /**
|
493 | 504 | * Clears all cached templates in this writer.
|
494 | 505 | */
|
495 | 506 | Writer.prototype.clearCache = function clearCache () {
|
496 |
| - this.cache = {}; |
| 507 | + if (typeof this.templateCache !== 'undefined') { |
| 508 | + this.templateCache.clear(); |
| 509 | + } |
497 | 510 | };
|
498 | 511 |
|
499 | 512 | /**
|
|
502 | 515 | * that is generated from the parse.
|
503 | 516 | */
|
504 | 517 | Writer.prototype.parse = function parse (template, tags) {
|
505 |
| - var cache = this.cache; |
| 518 | + var cache = this.templateCache; |
506 | 519 | var cacheKey = template + ':' + (tags || mustache.tags).join(':');
|
507 |
| - var tokens = cache[cacheKey]; |
508 |
| - |
509 |
| - if (tokens == null) |
510 |
| - tokens = cache[cacheKey] = parseTemplate(template, tags); |
| 520 | + var isCacheEnabled = typeof cache !== 'undefined'; |
| 521 | + var tokens = isCacheEnabled ? cache.get(cacheKey) : undefined; |
511 | 522 |
|
| 523 | + if (tokens == undefined) { |
| 524 | + tokens = parseTemplate(template, tags); |
| 525 | + isCacheEnabled && cache.set(cacheKey, tokens); |
| 526 | + } |
512 | 527 | return tokens;
|
513 | 528 | };
|
514 | 529 |
|
|
660 | 675 | to_html: undefined,
|
661 | 676 | Scanner: undefined,
|
662 | 677 | Context: undefined,
|
663 |
| - Writer: undefined |
| 678 | + Writer: undefined, |
| 679 | + /** |
| 680 | + * Allows a user to override the default caching strategy, by providing an |
| 681 | + * object with set, get and clear methods. This can also be used to disable |
| 682 | + * the cache by setting it to the literal `undefined`. |
| 683 | + */ |
| 684 | + set templateCache (cache) { |
| 685 | + defaultWriter.templateCache = cache; |
| 686 | + }, |
| 687 | + /** |
| 688 | + * Gets the default or overridden caching object from the default writer. |
| 689 | + */ |
| 690 | + get templateCache () { |
| 691 | + return defaultWriter.templateCache; |
| 692 | + } |
664 | 693 | };
|
665 | 694 |
|
666 | 695 | // All high-level mustache.* functions use this writer.
|
|
0 commit comments