JavaScript templating will make your life a lot easier

April 11th, 2012

I’ll admit it, when I first saw a tutorial explaining how to use JavaScript templates, I didn’t really see the point to it. I thought, if you really wanted to do something like that, you’d just use a server side language like PHP or just write it out in HTML. But then I built a site that didn’t have any server side code and had a page with a fair amount of divs that repeated the same divs to show information. WIth the styling the design called for, there was a bunch of HTML and it would add a lot of work and be hard to update. I took another look at JS templates and realized this would be a much easier way to do it. Here’s an example of when using a JS template would make your life a lot easier.

Let’s say we had some HTML like this:

1
2
3
4
5
6
7
8
9
10
<div class="box">
   <p>Name: James Bond</p>
   <p>Job: Spy</p>
   <p>Rating: Awesome</p>
</div>
<div class="box">
   <p>Name: Indiana Jones</p>
   <p>Job: Archaeologist</p>
   <p>Rating: Awesome</p>
</div>

There is nothing special here, just a couple of divs that list a couple of people, what they do and their rating. This is simple and would take 30 seconds to write. But let’s say that we might have to update the site a fair amount. Not enough that we need to set up a CMS but we’ll update it enough and with enough content that copy and pasting that code will be more work than it needs to be.

I like to use Handlebars.js. It’s super simple to use and it’s amazing how little code you need to set it up. First, just save this JS file, I’ve saved it as Handlebars.js. And then at the bottom of your HTML file you’ll need to link to it and jQuery:

1
2
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="js/Handlebars.js"></script>

Next we need to create the actual template. Handlebars.js uses curly braces {{ }} for the content in its templates. So what we need to replace in our template is the name, job and rating because we can leave the labels for those in the template because they’ll always be the same. The template will be inside a script tag with a special type attribute:

1
2
<script id="template" type="text/x-handlebars-template">
</script>

The type=”text/x-handlebars-template” tells our code that this is a template and to use it to create our HTML.

1
2
3
4
5
6
7
8
9
<script id="template" type="text/x-handlebars-template">
{{#each this}}
<div class="box">
   <p>Name: {{name}}</p>
   <p>Job: {{job}}</p>
   <p>Rating: {{rating}}</p>
</div>
{{/each}}
</script>

Wow, what is going on here? First off the {{#each this}}. This is just like a for loop in JavaScript. It’s just saying, for each of our items, use this HTML and add the content. Next we have {{name}}, {{job}} and {{rating}}. This is our content and we’ll set what goes there in the JavaScript we’ll write next. Finally we have {{/each}} which is the closing tag for our each loop. Simply put, for each item we have in our JS code, this will run and add the HTML to our page. If we have 20 items, our HTML will just have these nine lines instead of 180 lines of HTML. Now let’s write some JavaScript and make this work. We’ll create a JS file and link to it, I called my template-script.js. So you should have something that looks like this at the bottom of your HTML file.

1
2
3
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="js/Handlebars.js"></script>
<script src="js/template-script.js"></script>

Now our JS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
(function() {

   var container = $('#container'),
       people = [
           {
               name: 'James Bond',
               job: 'Spy',
               rating: 'Awesome'
           },
           {
               name: 'Indiana Jones',
               job: 'Archaeologist',
               rating: 'Awesome'
           },
           {
               name: 'Bruce Wayne',
               job: 'Superhero',
               rating: 'Total badass'
           },
           {
               name: 'Nicolas Cage',
               job: 'Actor',
               rating: 'Crazy'
            }
       ],
       template = Handlebars.compile($('#template').html());

   container.append(template(people));

})();

If you’ve used JavaScript at all, you should be able to figure out what’s going on here. First, we get the div with the id of container because that’s where we’re going to stick our generated HTML. Next, we create an array called people that contains all the content for our template. Inside the array, we have objects and each object has name, job and rating just like our template. Handlebars.js will insert the corresponding string into the template when it creates the HTML. Finally, we have a variable called template where we called Handlebars.js’ compile method on our template and we use jQuery’s html() method to get the HTML inside the script tags. Finally, we use jQuery’s append to add the template to the container and at the same time, we pass the people array to the template.

Now if we want to add or remove content from the page, we just edit this JavaScript file. In this example, which you can view here, it wouldn’t be that big of a deal to edit that HTML file, but in one with 500 lines of code, it would be a pain to hunt down the code you want to change. This way, you can just go into your 30 line JS file and add or remove 4 lines of code. I’m going to do another post showing some more complicated examples that really show the power of JavaScript templates.

2 Responses to JavaScript templating will make your life a lot easier

  1. Derek says:

    Woo, WTH! I thought that was PHP when I first saw the code…

  2. Derek says:

    Oh, and I suggest you to use doT.js. It is much faster, and easier.

Leave a Reply

Your email address will not be published. Required fields are marked *