Handlebars is a logic-less templating engine that dynamically generates your HTML page.
Handlebars is useful as it allows you seperate your logic-based code from your views. Too often I’ve done an Ajax request to get data from the server returned in JSON format, looped through the data and created one large concatenated string in the javascript file which would be then inserted to an element on the page. In this scenario, all the logic and HTML are bunched together. You’ll see shortly how using handlebars we will be able to separate this logic and make things much cleaner, and easier to manage.
To get started with handlebars, just go http://handlebarsjs.com/ where you can download the latest version or to get the CDN-hosted version, add the following tag in the head document at the top of the page;
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
To add templates to your page, the recommended way is to add a script tag to your page with type="text/x-handlebars-template”.
Consider the following HTML mixed with handlebars expressions;
<div id="myProjects"></div>
<script id="projectsTemplate" type="text/x-handlebars-template">
{{#each projects}}
<div class="col-4">
<div class="card">
<h3 class="card-title">{{title}}</h3>
<p>{{description}}</p>
<a href="{{url}}">View Site</a>
</div>
</div>
{{/each}}
</script>
As shown above, our expressions are wrapped in double curly braces “{{ }}
”. This tells handlebars to execute the variable or possibly helper function ( More about these later ) included within the curly braces.
Handlebars has a number of helper methods one of which is #each which as expected will iterate through our JSON data which we will pass to the template. The template above will iterate through each of our projects from a JSON Array and print the title “{{title}}
”, “{{description}}
” and {{url}}
which are values within the array.
To render our template above, we will have to create a script. I’ve created a number of scripts up to this point and there’s 4 lines of code which i’ve used over and over. After a while it becomes much clearer how it works and easier to remember. In coming up with JSON data to use, why not use the JSON data of projects currently on this site. Consider the following javascript file.
var projectsArray ={
"projects": [
{
"title": "ICT Skillnet",
"description": "Technology Ireland ICT Skillnet is a network of companies who collaborate to address skills needs within the technology sector.",
"url": "https://www.ictskillnet.ie",
"thumbnail": "../images/ict-skillnet-logo.jpg",
"status": "Complete",
"colour": "purple",
"gallery": ""
},
{
"title": "Bumpey",
"description": "Bumpey eliminates queues at venues using mobile technology. Increase sales and customer satisfaction by using Bumpey.",
"url": "http://bumpey.net/",
"thumbnail": "../images/bumpey.png",
"status": "Complete",
"colour": "purple",
"gallery": ""
}
]
};
var sourceProjects = document.getElementById("projectsTemplate").innerHTML;
var projectsTemplate = Handlebars.compile(sourceProjects);
var returntemp = projectsTemplate(projectsArray);
document.getElementById('myProjects').innerHTML += returntemp;
At the top we can see we have our JSON array of projects and after this array we see 4 lines of code where all the magic happens.
The first line we grab our template with id of “projectsTemplate” and copy it to a variable called sourceProjects. Just to note this is done in pure javascript but nothing is stopping you from using jQuery where applicable above.
In the second line, we compile this template using the Handlebars.compile() method which returns a functions that were going to use in the third line.
In the third line, we execute the template and the placeholders from our template wrapped in curly braces will be replaced by the correct values.
In the final line, we assign the generated html to a div with ID of “myProjects”. Once executed, the following was outputted to my screen which shows that it was successful with my projects title, description and link shown on screen.
Here the most obvious advantage is that our HTML is decoupled or seperate from our JavaScript which makes it much more easier to manage which will help us to presever our Seperation of Concerns principle.
Furthermore, Handlebars also provides us with the ability to define and use helper methods and block expressions as a way to cover more complex use cases while also helping to maintain our templates as clean and readable as possible.
User defined helper methods and more advanced usecases of handlebars are something of which I haven't included within this blog but will be covering in future posts.
For a more in-depth view of handlebars, please visit https://handlebarsjs.com/