Created
November 21, 2012 00:00
-
-
Save funkybrain/4122123 to your computer and use it in GitHub Desktop.
JavaScript: Handlebars Templating
This file contains hidden or 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
<!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