Skip to content

Instantly share code, notes, and snippets.

@lorenzoongithub
Created July 3, 2015 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lorenzoongithub/b2243eb4c522d51c9a0b to your computer and use it in GitHub Desktop.
Save lorenzoongithub/b2243eb4c522d51c9a0b to your computer and use it in GitHub Desktop.
handlebars.js
//
// http://handlebarsjs.com/
// minimal templating on steroids
//
load('http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars-v2.0.0.js');
// 1 Usage
source = "<p>Hello, my name is {{name}}. I am from {{hometown}}. I have " +
"{{kids.length}} kids:</p>" +
"<ul>{{#kids}}<li>{{name}} is {{age}}</li>{{/kids}}</ul>";
template = Handlebars.compile(source);
data = { "name": "Alan", "hometown": "Somewhere, TX",
"kids": [{"name": "Jimmy", "age": "12"}, {"name": "Sally", "age": "4"}]};
if (template(data)!='<p>Hello, my name is Alan. I am from Somewhere, TX. I have 2 kids:</p><ul><li>Jimmy is 12</li><li>Sally is 4</li></ul>') throw ''
// 2 Registering Helpers
Handlebars.registerHelper('link_to', function() {
return new Handlebars.SafeString("<a href='" + Handlebars.Utils.escapeExpression(this.url) + "'>" + Handlebars.Utils.escapeExpression(this.body) + "</a>");
});
context = { posts: [{url: "/hello-world", body: "Hello World!"}] };
source = "<ul>{{#posts}}<li>{{link_to}}</li>{{/posts}}</ul>"
template = Handlebars.compile(source);
if (template(context) !=="<ul><li><a href='/hello-world'>Hello World!</a></li></ul>") throw '';
// 3 Strings
Handlebars.registerHelper('link_to', function(title, options) {
return "<a href='/posts" + this.url + "'>" + title + "!</a>"
});
context = { posts: [{url: "/hello-world", body: "Hello World!"}] };
source = '<ul>{{#posts}}<li>{{{link_to "Post"}}}</li>{{/posts}}</ul>'
template = Handlebars.compile(source);
if (template(context)!=="<ul><li><a href='/posts/hello-world'>Post!</a></li></ul>") throw ''
// 4 Block Helpers
source = "<ul>{{#people}}<li>{{#link}}{{name}}{{/link}}</li>{{/people}}</ul>";
Handlebars.registerHelper('link', function(options) {
return '<a href="/people/' + this.id + '">' + options.fn(this) + '</a>';
});
var template = Handlebars.compile(source);
data = { "people": [
{ "name": "Alan", "id": 1 },
{ "name": "Yehuda", "id": 2 }
]};
if (template(data) !== '<ul><li><a href="/people/1">Alan</a></li><li><a href="/people/2">Yehuda</a></li></ul>') throw '';
// Partials
source = "<ul>{{#people}}<li>{{> link}}</li>{{/people}}</ul>";
Handlebars.registerPartial('link', '<a href="/people/{{id}}">{{name}}</a>')
template = Handlebars.compile(source);
data = { "people": [
{ "name": "Alan", "id": 1 },
{ "name": "Yehuda", "id": 2 }
]};
if (template(data) !== '<ul><li><a href="/people/1">Alan</a></li><li><a href="/people/2">Yehuda</a></li></ul>') throw '';
template(data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment