Handlebars + jQuery

Goal: add HTML components using jQuery without writing a whole bunch of HTML as a string. Instead, we’ll store HTML components in their own files, to be recycled as needed.

Old solution: 

$("#element").append("
<div><span class='myClass' id='" + relevantId + "'>" + relevantID + "</span>Some text about " + jsVariable + " element</div>
”)

Better solution: 

React.js has been been on my “to learn” list for far too long, and I swear I’m going to tackle in next – I think (hope) that it’ll solve my components issue.

Meanwhile, however, I’ve had to get around with jQuery, and have been running into a more and more persistent problem. Appending HTML with jQuery is easy for small bits of code, but ridiculous for larger snippets or components. Fortunately, I just found a solution: Handlebars.js, a front-end templating engine. We’re going to store our HTML snippets/components in their own files, and inject variables as needed. So, if we’re coding a Twitter clone, each post would be built from a post.html file, with relevant data inserted from JS using {{variable}}. Our files will look like this (sorry about the screenshot – WordPress formatting sucks)

Screen Shot 2017-09-28 at 4.31.37 PM

Handlebars will compile these HTML files with the variables we’ll provide it with. By the way, if this is looking familiar, it’s because it’s how things work in Angular and React, too (as far as I’ve seen), but we’re implementing it without the massive learning curve or intensity of using a whole front-end framework.

So, let’s get down to business. Here’s the step by step:

1. Add a Handlebars CDN link to your HTML file. Grab the latest version here. I recommend the handlebars.min.js file, since it’s a little smaller. Add the file in a ​script tag, before jQuery and your own JS script.

2. Create a .html component file following the convention above, inserting variables with this format: {{var}}. You can also use a bunch of other pre-built Handlebars conventions outlined in the documentation. I’ll call this file component.html.

3. Now, we’re gonna need to fetch the contents of the HTML file in your JS script. You can do this using jQuery’s $.get() method. The code will look like this:

$.get("component.html", function(data) {
  // do something with the data here...
}, 'html')

4. Next, a bit of Handlebars magic – this should go inside the function(data).

Note: function(data) is a callback function – it’s only run once $.get() fetches the contents of the external file. Because JS is asynchronous in nature, it will continue to run code written the $.get() section as the app waits for the $.get() to return the data from an external resource (in our case, a file).  So, in order to operate on the data after we fetch it, we pass in a callback function with the data as a parameter.

 var myTemplate = Handlebars.compile(data);

// this is where we store our variables
var context= {
 "name": "Biz Stone",
 "post": "I am a very important person at Twitter"
 };

// Handlebars magic injects our variables into our template
var compiledPost = myTemplate(context);

// this should look familiar
$("#postSection").append(compiledPost);

5. Voila! We’ve now appended a whole HTML snipped with our own variables. No more messy strings in our JS/jQuery code.

PS: With a little patience and regex string manipulation, it’s possible to get rid of Handlebars altogether and search the $.get() html response for variables encased in {{ }}, replacing them with your own values. However, for the sake of speed, I leave that exercise to the reader.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s