Skip to content

Instantly share code, notes, and snippets.

@Onasusweb
Created May 1, 2016 17:26
Show Gist options
  • Select an option

  • Save Onasusweb/e7fc1c4eaf81c5fcf9f81c29c3d63ede to your computer and use it in GitHub Desktop.

Select an option

Save Onasusweb/e7fc1c4eaf81c5fcf9f81c29c3d63ede to your computer and use it in GitHub Desktop.
How to combine JSON with Handlebars.js
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>How to render html with Handlebars.js</title>
<!-- Load handlerbars.js -->
<script src="js/handlebars.js"></script>
<!-- Load Jquery from CDN for easy DOM manipulations -->
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<!-- Simple handlebars template for a blog post, inside {{variable}} are variables we can afect with JS objects-->
<script id="simple-template" type="text/x-handlebars-template">
<h1>{{title}}</h1>
<p>
{{entry}}
</p>
</script>
<script type="text/javascript">
//wait for page to load
$(document).ready(function(){
// Extract the text from the template .html() is the jquery helper method for that
var raw_template = $('#simple-template').html();
// Compile that into an handlebars template
var template = Handlebars.compile(raw_template);
// Retrieve the placeHolder where the Posts will be displayed
var placeHolder = $("#main");
// Fetch all Blog Posts data from server in JSON
$.get("posts.json",function(data,status,xhr){
$.each(data,function(index,element){
// Generate the HTML for each post
var html = template(element);
// Render the posts into the page
placeHolder.append(html);
});
});
});
</script>
</head>
<body>
<!-- Insertion point for handlebars template -->
<div id="main" style="margin-left:100px">
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment