Complete HandlebarsJS Example with JQuery

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In the previous tutorial (which you should read first, if you haven’t already), we showed a complete handlebarsJS example without any dependencies except for the single handlebars.js file.  But in many other examples (including the ones on, you see things with dollar signs.  They are using HandlebarsJS with jQuery.  This is very common, as jQuery is quite heavily used. See jQuery tutorials if you are not familiar with jQuery.

Now here is a complete example where we use HandleJS with jQuery.  View running code here.

handlebarsjs jquery example

handlebarsjs jquery example

It is the same example as before.  The only difference are the lines in red.

First we reference the jQuery library from the CDN (content delivery network).  Whether we put this before or after the reference to the handlebars.js library does not matter, because handlebarsjs does not have a dependency on jQuery or anything else.

Then we have our script which must come after both the jQuery and handlebarsjs references.   This time we wrap our code  around with the jQuery document ready function.  The idea is the same, we want this code to run only when the document is ready (or loaded).

We obtain the source template by using the jQuery id selector to select the element with id=”person-template”.  Then we get the element’s html with the jQuery html() function.  Note the presence of the parenthesis here this time.

The code to have handlebarsjs compile the source into the template, and pass the context into the template to obtain the output is the same.

We put this output to the element with id=”nameoutput” using the jQuery id selector and html() function.