Sunday, February 12, 2017

handlebars.js

...is really simple to use. You can learn all there is to know in an hour. You can get it here and then, after looping in this one library, make a template inside a script tag like so:

<script id="myTemplate" type="text/x-handlebars-template">
   <table>
      <tr>
         <th>Foo</th>
         <th>Bar</th>
         <th>Baz</th>
         <th>Qux</th>
      </tr>
      {{#myCollection}}
         <tr>
            <td>{{foo}}</td>
            <td>{{bar}}</td>
            <td>{{baz}}</td>
            <td>{{#calculateQux foo bar baz}}{{/calculateQux}}</td>
         </tr>
      {{/myCollection}}
   </table>
</script>

 
 

Let's talk about how we could use this to fill in records in a div called someDivSomewhere with jQuery. The markup is pretty simple and it stays simple and if you are going to anything complicated at all you have to defer to a function in JavaScript to do so. In this example that function will be a calculateQux. To get this to work, you would need to make a function that takes in three variables at the signature to represent the foo, the bar, and the baz suggested in the markup above. Let's say that we just assign that function to a variable dubbed calculateQux also. Alright, with all of that in mind, the following code will get our div hydrated with our template.

var json = { myCollection: [ {foo:true,bar:"cat",baz:13}, {foo:false,bar:"dog",baz:42} ] };
Handlebars.registerHelper('calculateQux', calculateQux);
var stepOne = $("#myTemplate").html();
var stepTwo = Handlebars.compile(stepOne);
$("#someDivSomewhere").html(stepTwo(json));

 
 

Alright, the rest of what is happening should be easy to reverse engineer just by staring at it. We are handing in an object with a property called myCollection that is an array of objects which each have a foo, a bar, and a baz. We loop through them in the template while building a table. A fourth column for "Qux" has calculated values based on some other hijinks we have going on upstream in code. Yay! Bonus: The template in the stepOne variable may be pushed to and taken from localStorage!

No comments:

Post a Comment