Speed up development with full-stack environments for every branch.

Learn More

How to combine JSON with Handlebars.js [JavaScript, ajax and jQuery]

Forked from How to use custom helpers methods Handlebars.js.

3073 Runs 23415 Views 9842 Copies
Saved

Saved

lribeiro 90

lribeiro
published 4 years ago

<!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>
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).