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("", function(response, status) {
      if(status === "success") {

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

<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="{{}}" title="{{this.description}}"/>
    <a href=""><img alt="Endorse USERNAME on Coderwall" src="" />

Handlebars home:

Authored by
Francisco Villegas

Category: Javascript

Published date