Skip to content

Instantly share code, notes, and snippets.

@lorenzoongithub
Created July 3, 2015 21:06
Show Gist options
  • Save lorenzoongithub/5e0e99c2eac61d4c1ebb to your computer and use it in GitHub Desktop.
Save lorenzoongithub/5e0e99c2eac61d4c1ebb to your computer and use it in GitHub Desktop.
doT.js
load('http://olado.github.io/doT/doT.min.js');
// USAGE
//1. Compile template function
// var tempFn = doT.template("<h1>Here is a sample template {{=it.foo}}</h1>");
// 2. Use template function as many times as you like
// var resultText = tempFn({foo: 'with doT'});
// INTERPOLATION.
template = "<div>Hi {{=it.name}}!</div>"+
"<div>{{=it.age || ''}}</div>"
fn = doT.template(template);
data = {"name":"Jake","age":31};
result = fn(data);
if (result !== '<div>Hi Jake!</div><div>31</div>') throw '';
// EVALUATION
template = "{{ for(var prop in it) { }}\n<div>{{=prop}}</div>\n{{ } }}"
fn = doT.template(template);
data = {"name":"Jake","age":31,"mother":"Kate","father":"John","interests":["basketball","hockey","photography"],"contact":{"email":"[email protected]","phone":"999999999"}}
result = fn(data);
if (result !== '<div>name</div><div>age</div><div>mother</div><div>father</div><div>interests</div><div>contact</div>') throw '';
// CONDITIONALS
template = "{{? it.name }}\n"+
"<div>Oh, I love your name, {{=it.name}}!</div>\n"+
"{{?? it.age === 0}}\n"+
"<div>Guess nobody named you yet!</div>\n"+
"{{??}}\n"+
"You are {{=it.age}} and still don't have a name?\n"+
"{{?}}";
fn = doT.template(template);
data = {"name":"Jake","age":31};
result = fn(data);
if (result !== '<div>Oh, I love your name, Jake!</div>') throw '';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment