Skip to content

Commit e77fc7c

Browse files
AndrewLeedhamphillipj
authored andcommitted
Allow template caching to be customised (#731)
These changes allows the internal template cache to be customised, either by disabling it complete or providing a custom implementation of how templates are cached.
1 parent 8e52a4a commit e77fc7c

File tree

4 files changed

+124
-17
lines changed

4 files changed

+124
-17
lines changed

mustache.js

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -486,14 +486,27 @@
486486
* avoid the need to parse the same template twice.
487487
*/
488488
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+
};
490501
}
491502

492503
/**
493504
* Clears all cached templates in this writer.
494505
*/
495506
Writer.prototype.clearCache = function clearCache () {
496-
this.cache = {};
507+
if (typeof this.templateCache !== 'undefined') {
508+
this.templateCache.clear();
509+
}
497510
};
498511

499512
/**
@@ -502,13 +515,15 @@
502515
* that is generated from the parse.
503516
*/
504517
Writer.prototype.parse = function parse (template, tags) {
505-
var cache = this.cache;
518+
var cache = this.templateCache;
506519
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;
511522

523+
if (tokens == undefined) {
524+
tokens = parseTemplate(template, tags);
525+
isCacheEnabled && cache.set(cacheKey, tokens);
526+
}
512527
return tokens;
513528
};
514529

@@ -660,7 +675,21 @@
660675
to_html: undefined,
661676
Scanner: undefined,
662677
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+
}
664693
};
665694

666695
// All high-level mustache.* functions use this writer.

0 commit comments

Comments
 (0)