Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow template caching to be customised #731

Merged
merged 10 commits into from
Jan 11, 2020
32 changes: 24 additions & 8 deletions mustache.js
Original file line number Diff line number Diff line change
Expand Up @@ -486,14 +486,25 @@
* avoid the need to parse the same template twice.
*/
function Writer () {
this.cache = {};
this.templateCache = {
_cache: {},
set: function set (key, value) {
this._cache[key] = value;
},
get: function get (key) {
return this._cache[key];
},
clear: function clear () {
this._cache = {};
}
};
}

/**
* Clears all cached templates in this writer.
*/
Writer.prototype.clearCache = function clearCache () {
this.cache = {};
this.templateCache !== undefined && this.templateCache.clear();
};

/**
Expand All @@ -502,13 +513,15 @@
* that is generated from the parse.
*/
Writer.prototype.parse = function parse (template, tags) {
var cache = this.cache;
var cache = this.templateCache;
var cacheKey = template + ':' + (tags || mustache.tags).join(':');
var tokens = cache[cacheKey];

if (tokens == null)
tokens = cache[cacheKey] = parseTemplate(template, tags);
var isCacheEnabled = typeof cache !== 'undefined';
var tokens = isCacheEnabled ? cache.get(cacheKey) : undefined;

if (tokens == undefined) {
tokens = parseTemplate(template, tags);
isCacheEnabled && cache.set(cacheKey, tokens);
}
return tokens;
};

Expand Down Expand Up @@ -660,7 +673,10 @@
to_html: undefined,
Scanner: undefined,
Context: undefined,
Writer: undefined
Writer: undefined,
set templateCache (cache) {
defaultWriter.templateCache = cache;
}
};

// All high-level mustache.* functions use this writer.
Expand Down
Loading