Skip to content

Instantly share code, notes, and snippets.

@romuleald
Last active May 3, 2016 09:54
Show Gist options
  • Save romuleald/6183e8d15755721266ada1de71fc68af to your computer and use it in GitHub Desktop.
Save romuleald/6183e8d15755721266ada1de71fc68af to your computer and use it in GitHub Desktop.
get a template from a <script type="text/template"> and replace {{foo}} with {foo: 'bar'} → bar
var getTpl = (function () {
"use strict";
let cache = {};
var getCache = function (templateId) {
return cache[templateId];
};
var setCache = function (templateId, html) {
cache[templateId] = html;
};
/**
*
* @param {Object} data formed object that match in template {foo:'bar'} will replace {{foo}} with bar
* @param {String} templateId HTML attribute id
* @returns {string} HTMl template transformed
*/
var gettpl = function (data, templateId) {
let templateHTML = getCache(templateId);
if (getCache(templateId)) {
templateHTML = getCache(templateId);
}
else {
let tpl = document.getElementById(templateId);
templateHTML = tpl.innerHTML;
setCache(templateId, templateHTML);
}
//
return templateHTML.replace(/{{([^}]*)}}/g, function (search, result) {
return data[result];
});
};
return gettpl;
})();
export default getTpl;
@romuleald
Copy link
Author

add cache to speed performance

@romuleald
Copy link
Author

solve basic error of caching

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment