codeQuest

by Francisco Villegas

Javascript templates with Handlebars

Something very common when you are working with AJAX for example, is to write HTML code inside of your Javascript code, that in most of the cases makes you write ugly code.
Handlebars is a Javascript template engine and is one of the solutions to move the HTML off your Javascript code.

Example to display Coderwall badges using Handlebars.


$(document).ready(function () {
    $.getJSON("https://coderwall.com/USERNAME.json?callback=?", function(response, status) {
      if(status === "success") {
        showCoderwall(response.data)  
      }
    });
});

function showCoderwall(data) {
  var source   = $('#coderwall-template').html();
  var template = Handlebars.compile(source);
  var context = {data: data}
  var html    = template(context);
  $('#coderwall').html(html);
}


<script id="coderwall-template" type="text/x-handlebars-template">
    <h1>Coderwall Badges
    <ul class="coderwall_list">
        {{#each data.badges}}
        <li><img src="{{{this.badge}}}" alt="{{this.name}}" title="{{this.description}}"/>
        {{/each}}
    </ul>
    <a href="https://coderwall.com/USERNAME"><img alt="Endorse USERNAME on Coderwall" src="http://api.coderwall.com/USERNAME/endorsecount.png" />
</script>

Links:
Handlebars home: http://handlebarsjs.com


Authored by
Francisco Villegas

Category: Javascript

Published date