Step-by-step getting started tutorial on using Handlebars JS
In this tutorial, we will show you a step-by-step tutorial on how to get started using Handlebars JS.
Handlebars.js is a Javascript templating engine. Intersparse handlebars templating tags into an HTML page, and Handlebars.js will replace those tags with content at runtime on your browser. Although you can find how to get started at Handlebarsjs.com, their tutorial appears to be written for developers who are already well versed in templating engines. They show you bits and pieces, but not a complete example put together.
Here we will show you an example in its entirety …
If you run this in your browser, you should see the following (as linked here)…
Now for the step-by-step on how we got this …
1. Start with a basic HTML page (we call it handlebarsjs-example.html) …
When run in a browser, you see …
2. Now we add an HandlebarsJS template fragment inline at the bottom of the HTML page (right before the closing </body>)…
The template is bounded by <script> tag of type “text/x-handlebars-template”. So the browser will not display its contents during normal rendering. We see this in the browser…
We gave the script tag an arbitrary id of “person-template” because we will need to access its content later.
3. Inside the template, we have two handlebarsJS template variable tags: “firstname” and “lastname”. We want that these template variables to be replaced by the actual data. This is where handlebarsjs comes in. Go to http://handlebarsjs.com/ and click the download button. There is only one handlebars.js file (version 1.0.0 at this time) that you can copy and paste the content to your file “handlebars.js”. For convenience, we place this file right next to our handlebarsjs-example.html file.
So we include a script reference to this handlebars.js library…
4. Now we add our own Javascript which we wrap in an onload event to ensure that our javascript runs only after everything is loaded…
5. We access our handlebarsjs template via the “person-template” id and get the innerHTML into the “source” Javascript variable…
6. We call Handlebars to compile the source into a template …
7. We set some data in the context…
8. We pass that context to the template to get an output…
9. We place that output into our HTML …
Note that we had to give a div of id=”nameoutput” so that the script is able to reference it and output the result into the innerHTML of that element.
Most people like to using jQuery and many examples out there show it using jQuery. If you want to use jQuery with HandlerbarsJS, read the next tutorial here.