Skip to content

Instantly share code, notes, and snippets.

@funkybrain
Created November 21, 2012 00:00
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 funkybrain/4122123 to your computer and use it in GitHub Desktop.
Save funkybrain/4122123 to your computer and use it in GitHub Desktop.
JavaScript: Handlebars Templating
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Handlebars</title>
<style>
span {
color: red;
font-size: 0.5em
}
</style>
</head>
<body>
<ul class="tweets">
<script id="template" type="text/x-handlebars-template">
{{#each this}}
<li>
<h2>{{fullName author}} - {{#if age}}<span>{{age}}</span>{{/if}}</h2>
<p>{{tweet}}</p>
{{#unless quote}}
<h5>Author does not have a quote</h5>
{{/unless}}
</li>
{{/each}}
</script>
</ul>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.js"></script>
<script type="text/javascript">
// always place code in SIAF to avoid creating global variables
(function(){
// create an object that is itself an array of objects
var data =[
{
author: {first: 'Jeffrey', last: 'Way'},
tweet: '30 days to learn jquery rocks',
age: '27'
},
{
author: {first: 'John', last: 'Wayne'},
tweet: 'Rio Bravo was awseucj',
quote: 'I kill for a living'
}];
// Helpers
Handlebars.registerHelpre('fullName', function( author ){
return author.first + ' ' + author.last;
});
// this returns a function
var template = Handlebars.compile( $('#template').html() );
// and then append it to your DOM
$('ul.tweets').append(template(data));
})();
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment