Ein kurzer Post über die Javascript Templating Engine Handlebars.js.

Der Hauptnutzen einer Javascript Templating Engine ist es, Javascript und HTML von einander zu entkoppeln, was vor allem bei größeren Projekten zu einer besseren Wartbarkeit und Übersicht führt.

Ein kleines Beispiel:

typischer HTML und JS Mix
HTML:

<html>​
 <head>​
 <script type="text/javascript" src="jquery-1.9.1.min.js"></script>​
 </head>​
   <body>​
    The List of Shoes:
    <ul class="shoesNav"></ul>​    
   </body>​
</html>

das dazugehörige Javascript (jQuery)

$(function  () {
 
​var shoesData = [{name:"Nike", price:199.00 }, {name:"Loafers", price:59.00 }, {name:"Wing Tip", price:259.00 }];
​
​function updateAllShoes(shoes)  {
​var theHTMLListOfShoes = "";
​
shoesData.forEach (function (eachShoe)  {
​// Note the coupling and mixing of HTML and JavaScript; it is tedious to follow​
 theHTMLListOfShoes += '
  • ' + '' + eachShoe.name + ' -- Price: ' + eachShoe.price + '
  • '; }); return theHTMLListOfShoes; } $(".shoesNav").append (updateAllShoes(shoesData)); ​ });

    clean Approach mit Handlebars Syntax
    HTML:

    <script id="shoe-template" type="x-handlebars-template">​
       {{#each this}}​
        <li class="shoes"><a href="/{{name}}">{{name}} -- Price: {{price}} </a></li>​
        {{/each}}
    

    ​ 


    und das Javascript mit Handlebars-Syntax:

    $(function  () {
      var shoesData = [{name:"Nike", price:199.00 }, {name:"Loafers", price:59.00 }, {name:"Wing Tip", price:259.00 }];
       //Get the HTML from the template   in the script tag​
        var theTemplateScript = $("#shoe-template").html(); 
    ​
       //Compile the template​
        var theTemplate = Handlebars.compile (theTemplateScript); 
        $(".shoesNav").append (theTemplate(shoesData)); 
    ​
    ​//We pass the shoesData object to the compiled handleBars function​
    ​// The function will insert all the values from the objects in their respective places in the HTML and returned HTML as a string. Then we use jQuery to append the resulting HTML string into the page​
    });

    Wie man durch die beiden Code-Beispiele sehr gut sehen kann, ist mit einer Templating-Engine Javascript und HTML sauber getrennt.

    Further Reading

    Ein schlankes Handlebars.js Tutorial für den Einstieg in diese effiziente Templating Sprache findet ihr hier.