Last active
May 3, 2016 09:54
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
solve basic error of caching