Last active
April 24, 2016 07:06
-
-
Save zlumer/fbaefc503279e4fe0ad6 to your computer and use it in GitHub Desktop.
doT template preloader for browser
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
(function (doT) { | |
var templates = {}; | |
var scripts = Array.prototype.slice.call(document.getElementsByTagName('script')); // load all scripts | |
for (var i = 0; i < scripts.length; i++) { // filter out template script tags | |
var script = scripts[i]; | |
if (script.type == "text/dot-template") { | |
var name = script.id || script.getAttribute('name') || script.getAttribute('data-name'); | |
templates[name] = script.innerHTML; // store template for later use | |
script.parentNode.removeChild(script); // remove template from DOM | |
} | |
} | |
var cache = {}; | |
/** | |
* Get template function by name. | |
*/ | |
doT.tmpl = function (name) { | |
if (!templates[name]) | |
throw new Error("template \"" + name + "\" not found!"); | |
if (!cache[name]) | |
cache[name] = doT.template(templates[name]); | |
return cache[name]; | |
}; | |
/** | |
* Render template with provided data. | |
*/ | |
doT.render = function (name, data) { | |
var tmpl = doT.tmpl(name); | |
if (!tmpl) | |
return undefined; | |
return tmpl(data); | |
}; | |
})(window.doT); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
doT template preloader for browsers.
No frameworks/libraries required, just doT itself.
Usage:
1. Embed some templates into your HTML with
type="text/dot-template"
and any ofid
/name
/data-name
.2. Include the script in your HTML after doT.
3. Render the result.