Share Tweet Reccomend

JavaScript Templates with Handlebars.js

Templates are a very important part of modern day web applications written in JavaScript. Templating essentially encompasses the visual UI (user interface) components of these applications by rendering different “views” depending on the current state of the application. A “view” can be thought of as a certain type of layout. For example, when you sign in to an application and go to your account settings, you might be looking at a “profile” view. Or, if you were using an e-commerce application and you were browsing the site’s inventory, you might be looking at a “products” view. These views are dynamic in nature because they receive data that gets sent to them and then they render that data out in a manner that is meaningful and useful to the user.

There are many different templating libraries that can be used to render views in a JavaScript web application. No one library is necessarily better than another and it is likely that they all have their various strengths and weaknesses. We have looked at a couple of ways to do templates in Backbone.js applications and we’ll revisit one of the libraries used there: Handlebars.js. Handlebars is one of the templating libraries that I like very much for it’s simplicity and intuitive syntax. The Handlebars.js homepage has some very clear straightforward examples that allow you to jump right in to learning how to use it.

Handlebars template setups will look something like the following…

<!DOCTYPE html>
<html>
<head>
<title>Handlebars</title>
<script src="js/jquery.js" type="text/javascript"></script> 
<script src="js/handlebars.js" type="text/javascript"></script> 
</head>
<body>
<div class="content"></div>
<script id="artist-list-template" type="text/x-handlebars-template">
<h1>{{ title }}</h1>
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Hometown</th>
      <th>Favorite Color</th>
    </tr>
  </thead>
  <tbody>
      {{#each artists}}
      <tr>
          <td>{{ name }}</td>
          <td>{{ hometown }}</td>
          <td>{{ favoriteColor }}</td>
      </tr>
      {{/each}}
  </tbody>
</table>
</script>
</script>
<script type="text/javascript">
var data = {
    title: 'Artist Table', 
    artists: [
        { id: 1, name: 'Notorious BIG', birthday: 'May 21, 1972', hometown: 'Brooklyn, NY', favoriteColor: 'green' },
        { id: 2, name: 'Mike Jones', birthday: 'January 6, 1981', hometown: 'Houston, TX', favoriteColor: 'blue' },
        { id: 3, name: 'Taylor Swift', birthday: 'December 13, 1989', hometown: 'Reading, PA', favoriteColor: 'red' }
    ]
}
var source = jQuery('#artist-list-template').html();
var template = Handlebars.compile(source);
var html = template(data);
jQuery('.content').html(html);
</script>
</body>
</html> 

What we are doing here is passing data (in this case the JSON object in our data into) our artist list template (the one with id: #artist-list-template). Note that with our array or artists inside the {{ #each artists }} block (where we are looping over an array of JSON objects) the context has changed so we can directly refer to the artist name, hometown, and favoriteColor properties in for each item

In this example, we are using a static data object that we have created inline but in a real application it’s likely that you’d be getting that data via AJAX requests to APIs somewhere. But whether you get your data from a server or create it locally, the important part is that data can then be passed into the Handlebars template to be displayed by Handlebars. That is where using a templating engine becomes very efficient and very useful. The view/template does not need to worry about handing anything in the data. All of the code to handle getting data and then searching and sorting through it can be handled elsewhere. All your Handlebars template has to worry about is displaying the “final result” that your code generated elsewhere has produced.

There is also support for doing “multi-level” references of you have a JSON object that is x layers deep, you can refer to the properties inside it by normal dot syntax you might be familiar with.

<div class="entry">
  <h1>{{title}}</h1>
  <h2>By {{author.name}}</h2>
  <div class="body">
    {{body}}
  </div>
</div>
<script type="text/javascript">
var data = {
  title: "A Blog Post!",
  author: {
    id: 42,
    name: "Joe Smith"
  },
  body: "This is the text of the blog post"
};
</script>

And there is even the possibility of doing conditionals via the built-in helper methods. For example, here is an if conditional in a Handlebars template where if a property does not exist or is null in an object that is passed to the view, a different “block” of code will be rendered.

<div class="entry">
  {{#if author}}
    <h1>{{firstName}} {{lastName}}</h1>
  {{else}}
    <h1>Unknown Author</h1>
  {{/if}}
</div>

And this is just scratching the surface. There are many other features and functionality that Handlebars.js provides. So head on over to the Handlebars.js homepage to start taking a look through the examples there to see what can be accomplished.

As we have seen Handlebars.js is very useful for creating a view layer in single-page JavaScript applications. Ember.js applications Handlebars.js by default, but you could certainly integrate Handlebars into applications built with other libraries. One of these examples is discussed here. But it should also be noted that there is also support for using Handlebars to render HTML on the server in a Node.js application before it is sent to the browser. For example, if you were building an Express.js application, you could use the express-handlebars module to handle the view component of your appplication by creating some dynamically generated HTML to server up to the browser. For more info on Node.js see this entry here, and for more info on building Express.js applications on top of Node.js see this entry here.

Hopefully you have found this discussion of Handlebars.js useful and that you consider using it for your templating needs in your next application. Download the files below to play around with this useful library…

Download Files
Share Tweet Reccomend

Express.js Authentication

Now we will discuss how to implement authentication in Express.js. Express.js was discussed previously in the Introduction to Express.js. In the discussion there, we looked at how Express is a web-application framework just like CodeIgniter, Django, or Laravel except instead of running on something like Apache or Ngnix, it runs on Node.js and instead of being written in PHP or Python, it is written in JavaScript. Before looking at the following section, it might be a good idea to be familiar with Express.js by reading the introduction to Express and be familiar with Node.js as well. A Node.js Primer will help you with that.

When you think authentication in web development, you think logging in and logging out. Note that this is a little bit different from authorization, which has more to do with whether a logged in user has the permissions to do a certain action on a website. This the reason that you have different roles such as “Administrator,” “Editor,” and “User” defined within different systems. For this section we’ll focus more on authentication, but a lot of the ways that you handle authentication can also be extended upon to implement authorization.

Session-Based Authentication

When you speak of authentication in modern web applications, there are a number of different implementations you could be talking about. One of the more traditional approaches is the use of sessions. Sessions go back as far as anyone can remember with anything having to do with the web. Express.js supports sessions and you can use them just as you would in other languages like PHP.

Place the following code in a file called server.js. Obviously, in a real application we’d want to separate the markup we’re returning out into views and use a templating language to render them like we did in the introduction to Express. But for now, this will do just to serve for purpose of example…

var express = require('express');
var app = express();
app.use(express.bodyParser());
app.use(express.cookieParser('shhhh, very secret'));
app.use(express.session());
function restrict(req, res, next) {
  if (req.session.user) {
    next();
  } else {
    req.session.error = 'Access denied!';
    res.redirect('/login');
  }
}
app.get('/', function(request, response) {
   response.send('This is the homepage');
});
app.get('/login', function(request, response) {
   response.send('<form method="post" action="/login">' +
  '<p>' +
    '<label>Username:</label>' +
    '<input type="text" name="username">' +
  '</p>' +
  '<p>' +
    '<label>Password:</label>' +
    '<input type="text" name="password">' +
  '</p>' +
  '<p>' +
    '<input type="submit" value="Login">' +
  '</p>' +
  '</form>');
});
app.post('/login', function(request, response) {
    var username = request.body.username;
    var password = request.body.password;
    if(username == 'demo' && password == 'demo'){
        request.session.regenerate(function(){
        request.session.user = username;
        response.redirect('/restricted');
        });
    }
    else {
       res.redirect('login');
    }	
});
app.get('/logout', function(request, response){
    request.session.destroy(function(){
        response.redirect('/');
    });
});
app.get('/restricted', restrict, function(request, response){
  response.send('This is the restricted area! Hello ' + request.session.user + '! click <a href="/logout">here to logout</a>');
});
app.listen(8124, function(){
    console.log('Server running...');
});

Now if you run the following command in the same directory as server.js…

node server

and then open up your browser to http://localhost:8124 you can see the homepage as defined by the default route.

Read More »

Share Tweet Reccomend

Introduction to Express.js

Express is one of the more popular solutions for running a web-server and creating web applications using Node.js. If you are not familiar with Node.js and what it is all about, this primer has an introductory discussion on some of the concepts behind Node.js and some of the potential benefits it offers for certain solutions in certain environments. I highly recommend reading that first before reading what follows if you are not yet acquainted with Node.js. Express is even mentioned a bit in there as well.

Express is a web-application framework just like Django, CodeIgniter, or Laravel. The only difference is that instead of running on something like Apache, it runs on Node.js and instead of being written in PHP or Python, it is written in JavaScript. There are other web application frameworks that run on top of Node.js (like Hapi) but Express is one of the more popular ones.

Below is a link to what we will be building in this section…

Demo Files

Express, like other Node.js installations, comes in the form of a module. You can use a utility called “npm” to install it using the command line. To install Express we just have to type the following into our Node.js command line…

$ npm install express

This will download all of the files that Express requires (dependencies) and will place them in a folder called “node_modules”.

Now that we have Express installed we can get started. Create a file named server.js and add the following…

var express = require('express');
var app = express();
app.get('/', function(request, response) {
   response.send("<h1>Our Express App</h1>");
});
app.listen(8124);

Then open up your favorite terminal (like BASH) and type the following…

$ node server.js

If you open a browser and type in http://127.0.0.1:8124/ you should see the text appear. The great thing about Express is that right out-of-the-box we can use it to define some routes and build an entire web application. If you have used Lavavel or the Slim PHP Framework or something similar this might look familiar. We can also define routes for the other HTTP verbs: POST, PUT, and DELETE. We can return HTML or we can use it to create an API that returns XML or JSON. The possibilities for what we can do with it are all there.

Read More »