Skip to content

Instantly share code, notes, and snippets.

@zlumer
Last active April 24, 2016 07:06
Show Gist options
  • Save zlumer/fbaefc503279e4fe0ad6 to your computer and use it in GitHub Desktop.
Save zlumer/fbaefc503279e4fe0ad6 to your computer and use it in GitHub Desktop.
doT template preloader for browser
(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);
@zlumer
Copy link
Author

zlumer commented Jun 1, 2015

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 of id/name/data-name.

<script type="text/dot-template" data-name="user-profile"><div>Name:{{= it.name }}</div></script>

 2. Include the script in your HTML after doT.

<script src="//cdnjs.cloudflare.com/ajax/libs/dot/1.0.3/doT.min.js"></script>
<script src="[PATH_TO_FILE].js"></script>

 3. Render the result.

var profile = doT.render("user-profile", { name: "John" });
document.getElementById('container').insertAdjacentHTML("beforeend", profile); // vanilla JS
$('#container').append(profile); // or jQuery

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