Last active
October 15, 2022 03:51
-
-
Save LeCoupa/6176077a9a8e2ad00eda to your computer and use it in GitHub Desktop.
Handlebars CheatSheet --> https://github.com/LeCoupa/awesome-cheatsheets
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
// 1. Define a helper. | |
// http://handlebarsjs.com/expressions.html#helpers | |
// also note: Helpers receive the current context as the this context of the function. | |
Handlebars.registerHelper('link', function(object) { | |
return new Handlebars.SafeString( | |
"<a href='" + object.url + "'>" + object.text + "</a>" | |
); | |
}); | |
Handlebars.registerHelper('link', function(text, options) { | |
var attrs = []; | |
for(var prop in options.hash) { | |
attrs.push(prop + '="' + options.hash[prop] + '"'); | |
} | |
return new Handlebars.SafeString( | |
"<a " + attrs.join(" ") + ">" + text + "</a>" | |
); | |
}); | |
// 2. Compilation and Execution. | |
// You can deliver a template to the browser by including it in a <script> tag. | |
// <script id="entry-template" type="text/x-handlebars-template"> | |
// template content | |
// </script> | |
// check also precompilation: http://handlebarsjs.com/precompilation.html | |
var source = $("#entry-template").html(); | |
var template = Handlebars.compile(source); | |
// execution: http://handlebarsjs.com/execution.html | |
var context = {title: "My New Post", body: "This is my first post!"} | |
var html = template(context); | |
// 3. Block Expressions. | |
// http://handlebarsjs.com/#block-expressions | |
// {{#list people}}{{firstName}} {{lastName}}{{/list}} | |
templateContext = { | |
people: [ | |
{firstName: "Yehuda", lastName: "Katz"}, | |
{firstName: "Carl", lastName: "Lerche"}, | |
{firstName: "Alan", lastName: "Johnson"} | |
] | |
} | |
Handlebars.registerHelper('list', function(items, options) { | |
var out = "<ul>"; | |
for(var i=0, l=items.length; i<l; i++) { | |
out = out + "<li>" + options.fn(items[i]) + "</li>"; | |
} | |
return out + "</ul>"; | |
}); | |
Handlebars.registerHelper('if', function(conditional, options) { | |
if(conditional) { | |
return options.fn(this); | |
} else { | |
return options.inverse(this); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks.