Skip to content

Instantly share code, notes, and snippets.

@frankV
Created June 26, 2013 15:59
Show Gist options
  • Save frankV/5868679 to your computer and use it in GitHub Desktop.
Save frankV/5868679 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Handelbars Example 2</title>
<script src="js/handlebars.js"></script>
<!-- notice this will not display until the data is populated -->
<script id="result-template" type="text/x-handlebars-template">
<h2>Your Favorite Things</h2>
{{#if things}}
<ul>
{{#each things}}
<li>{{this}}</li>
{{/each}}
</ul>
{{else}}
<p>
Apparently, you like nothing. Poor you.
</p>
{{/if}}
</script>
</head>
<body>
<h2>List of Things</h2>
<p>
Enter a comma-separated list of things you like.
</p>
<input type="text" id="things" placeholder="Things you like..."><br/>
<button id="demoButton">Demo</button>
<div id="resultDiv"> <!-- the template will display here --> </div>
<!-- le javascript -->
<script>
document.addEventListener("DOMContentLoaded", function() {
//Get the contents from the script block
var source = document.querySelector("#result-template").innerHTML;
//Compile context into a template
template = Handlebars.compile(source);
document.querySelector("#demoButton").addEventListener("click", function() {
var things = document.querySelector("#things").value;
if(things.length) var arrThings = things.split(",");
// html is an array of "things" objects
var html = template({things:arrThings});
document.querySelector("#resultDiv").innerHTML = html;
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment