9bit Studios » Handlebars.js https://9bitstudios.com Web Design, Themes, & Applications Sun, 22 Mar 2015 00:36:38 +0000 en-US hourly 1 https://wordpress.org/?v=4.1.1 Creating an MVC Express.js Application (Part 2) https://9bitstudios.com/2014/12/creating-an-mvc-express-js-application-part-2/ https://9bitstudios.com/2014/12/creating-an-mvc-express-js-application-part-2/#comments Fri, 19 Dec 2014 19:41:27 +0000 https://9bitstudios.com/?p=1010 Previously, in an earlier installment we discussed some initial considerations for creating an application in Express.js following the Model View Controller (MVC) design pattern. We’ll pick up where we left off in what follows. The focal point will center around middleware and configuration…

Middleware

One of the things that we are going to want to implement in our application is middleware. There is a pretty good list of Express.js middleware in the Express.js project. Middleware is an important component of Express.js applications. You couple probably think of a middleware function or method as a function that runs on every request/response cycle at whatever point you want to specify. For example, if you wanted to see if the current user who is making the request is authenticated on every single request, you might have this authentication check run in a middleware function before issuing the response. That’s just one example, but there are many other pieces of functionality that you can run within middleware functions.

So let’s add some of the common Express.js middlewares. One useful middleware utility that we can use is a logging component. This will give us information about all of the requests made as our application runs. Express.js uses something called Morgan to accomplish this.

To add middleware, we’re going to want to add it to our package.json file as a dependency. So let’s update our package.json file to look like the following

{
    "name": "MVC-Express-Application",
    "description": "An Express.js application using the MVC design pattern...",
    "version": "0.0.1",
    "dependencies": {
        "express": "4.4.4",	
        "express-handlebars": "1.1.0",
        "morgan": "1.1.1",
    }
}

Don’t forget that we have to install our new module as well. Fortunately, Node.js and npm make this easy. All we have to do is run $ npm install again and all of our packages will be updated…

$ npm install

Now that our dependency is installed, we need to add a reference to it in our main application file…

var logger = require('morgan');

Let’s add the following lines of code to our main app.js file…

/* Morgan - https://github.com/expressjs/morgan
 HTTP request logger middleware for node.js */
app.use(logger({ format: 'dev', immediate: true }));

Now if we run our application and look at our CLI window we can see all the requests being output on every request response cycle. And just like that, we have made use of our first middleware.

We will also want a utility to log any errors that occur while we are doing development. So let’s add an error handling utility to our package.json file…

{
    "name": "MVC-Express-Application",
    "description": "An Express.js application using the MVC design pattern...",
    "version": "0.0.1",
    "dependencies": {
        "express": "4.4.4",	
        "express-handlebars": "1.1.0",
        "morgan": "1.1.1",
        "errorhandler": "1.1.1"
    }
}

After we run $npm install again to install the error handling module, we again need to add a reference to it…

var errorHandler = require('errorhandler');

Now we can also add the following code to our main application file as well…

/* errorhandler - https://github.com/expressjs/errorhandler
 Show errors in development. */
app.use(errorHandler({ dumpExceptions: true, showStack: true }));

We’d probably want to comment this out if we were ever to move our application into a production environment, but for development this is a very handy thing to have for debugging because it can tell us where, when, and how any errors in our application are occurring.

We are not just limited to using middleware that Express.js provides. We can also create our own as well. Let’s add a directory called “utilities” to our project and put a Middleware.js file in this folder.

We will want to make sure that we include a reference to this file in our main application file.

var Middleware = require('./utilities/Middleware');

What can we add to our Middleware.js file? Well, whatever we want really. For example, we can add something that will check to see if there is a set value in the query string and tell our application to show a notification depending what is set. Notifications such as “Profile updated successfully” or “There was an error uploading the file” or other relevant messages are a very important part of a good user-experience in any application. So our application is going to need these as well and using a middleware function to handle this aspect of functionality seems like a decent approach.

Recall that previously we had appended a “pageInfo” object to the response pass to our views. We will utilize this same approach here and add a “notifications” property to this object. Because the middleware runs *before* the controllers that handle our routes, we can initialize the pageInfo property here instead…

exports.AppendNotifications = function(request, response, next) {
    
    response.pageInfo = {};
    response.pageInfo.notifications = {};

    if(request.param('success')) {
	response.pageInfo.notifications.success = "Success!"
    }
    else if (request.param('error')){
	response.pageInfo.notifications.error = "Sorry, an error occured"
    }
    
    next();
    
};

Notice the next(); function at the end of our custom middleware function. This is a common function utilized in middleware implementations. Basically all it does is say “go to the next middleware function, if any.” If there are no more middleware functions to run, execution of the application will just continue on as normal. This way, you can group middleware functions together to run sequentially in the order that you want to specify.

Now we can add our middleware to our main application file, just as we did with the Express.js proved middleware…

app.use(Middleware.AppendNotifications);

Now that we have our middleware in place we’ll need to update our views to be able to show the notifications. Fortunately, we can add something to show these notifications in our Main.handlebars layout…

<!DOCTYPE html>
<html lang="en">
    <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta name="description" content="">
      <meta name="author" content="">
      <link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon"> 

      <title>MVC Express Application</title>

    </head>

    <body>

        <div class="notifications">
    
            {{#if notifications.success}}
            <div class="success">
                {{ notifications.success }}
            </div>
            {{/if}}
    
            {{#if notifications.error}}
            <div class="error">
                {{ notifications.error }}
            </div>
            {{/if}}

        </div>

        {{{body}}}
    </body>
</html>

This uses the conditional {{#if }} syntax that the Handlebars.js templating engine provides. This is one of the built-in helpers of Handlebars. You can read more about conditionals and other helpers here.

Now if you navigate to one of our routes and add the query string to the end e.g. https://localhost:1337/?success=true or https://localhost:1337/other?error=true we can see the notification appear. Right now the message for each parameter is just a static string, but with a little bit of further tweaking we could customize the notification that appears based on some other parameters as well. In the normal flow of application, we would usually do a redirect with these parameters after performing some action depending on the outcome. But we don’t really have that functionality in our application yet so to see the notifications we just have to add them end of of our URL.

We will use middleware more extensively as the development of our application matures. But for now this illustration shows how middleware can be implemented in useful ways.

Now we’ll shift gears and talk about configuration, which is another component that is important to any well-structured application.

Configuration

If you have used any framework in any language — such as Laravel (PHP) or Django (Python) — you know that it is often a good idea to have a configuration file where you can store application variables that will remain constant throughout the application. These sorts of settings include things like database names, connection strings, root URLs, ports, or anything else that you want to utilize. It will also give you a place where you can easily make changes to settings when moving from one environment to another, e.g. when moving from your development environment to production

So we’ll want to create a config.js file for our application as well. Create a config.js file and place it in the main top-level project folder. In config.js place the following code

var config = {};

config.development = {

    application: {
	port: 1337
    }
    
};

config.production = {

    application: {
	port: 80
    }    
    
};

config.environment = 'development';

module.exports = config;

And we’ll need to make sure that we include a reference to our config file in our main application file.

var config = require('./config');

So, for example, if we do something like changing the following line in our main application file from…

app.set('port', 1337);

to

app.set('port', config[config.environment].application.port);

we are making use of our configuration file because the value of the port we have set will be looked up in the config file. Now if we ever want to push our application from development to staging to production, the only thing we need to edit is the config.js file because, we have a way to quickly and easily set our “environment”. So if we change that string value from “development” to “production,” all of the variables within the object will be switched over across our application. The rest of the application will remain unchanged.

The great thing about this too is that as we add more features and functionality to our application, we can store the needed values for these in our config.js file. This way our application will scale well as it grows and progresses on. Other values important in an application such as database connection strings, credentials, SMTP servers, and strings used for creating hashes and tokens can all be stored in a configuration file. At the end of it all, our config.js file might end up looking more like the following…

var config = {};

config.development = {
    
    database: {
	name: 'MVCApplication',
	host: 'localhost',
	port: '27017',
	credentials: '' // username:password@
    },
    smtp: {
	username: "username",
	password: "password",
	host: "smtp.gmail.com",
	port: 587,
	ssl: false
    },
    application: {
	port: 1337,
	cookieKey: '8YQM5GUAtLAT34'
    }
    
};

config.production = {
    
    database: {
	name: 'proddb',
	host: 'localhost',
	port: '8080',
	credentials: 'admin:password@' // username:password@
    },
    smtp: {
	username: "username",
	password: "password",
	host: "smtp.yourmailserver.com",
	port: 25,
	ssl: false
    },    
    application: {
	port: 80,
	cookieKey: '5SCjWfsTW8ySul'
    }    
    
};

config.environment = 'development';

module.exports = config;

This is one way to do configuration. Keep in mind that it’s not the only way and there are many other ways you could implement a configuration component in your application. It will probably often come down to a matter of personal preference. The important thing is that you do it in some manner or another to give your application a greater degree of flexibility as you move between environments for development, test, and production. You’ll be glad that you did and you’ll thank yourself later.

Summary

Overall, in this section we looked at 2 important aspects of creating an Express.js application: middleware and configuration. In upcoming explorations, we’ll take a look at some more advanced templating with our views as well as data access and authentication. But for now, it’s good to digest this information in small portions. So feel free download the files below and play around with application configuration and middleware.

Download Files
]]>
https://9bitstudios.com/2014/12/creating-an-mvc-express-js-application-part-2/feed/ 0
Using Templates in Backbone.js https://9bitstudios.com/2013/05/using-templates-in-backbone-js/ https://9bitstudios.com/2013/05/using-templates-in-backbone-js/#comments Wed, 15 May 2013 22:16:02 +0000 https://9bitstudios.com/?p=846 One of the more important components of Backbone.js is using templates. What are templates? Templates are essentially pieces of markup that you can use to create a bunch of different reusable copies of that markup (including all the styles and hierarchy that you want) but populating each component with different data. Used in combination with views, they are great for doing such as iterating over a collection of models to display a list of data for some purpose. You’ll see how it all fits together in what follows.

By default, Backbone.js uses the templating engine of Underscore.js which makes sense because Backbone has a hard dependency on Underscore. However, if you’re not a big fan of the way that Underscore does templating or you just want to use another templating engine, Backbone allows for that as well. The possibilities are limitless. But let’s first take a look at an Underscore.js template because that will work out of the box with Backbone.js. You do not need to load up anything else to use templates.

To get started, let’s define a model and instantiate a few models…

var Artist = Backbone.Model.extend({
    defaults: {
        name: 'New Artist',
        birthday: 'January 1, 1970',
        hometown: 'Los Angeles, CA',
        favoriteColor: 'blue',
    }
});

var biggie = new Artist({ id: 1, name: 'Notorious BIG', birthday: 'May 21, 1972', hometown: 'Brooklyn, NY', favoriteColor: 'green' });
var mike = new Artist({ id: 2, name: 'Mike Jones', birthday: 'January 6, 1981', hometown: 'Houston, TX', favoriteColor: 'blue' });
var taylor = new Artist({ id: 3, name: 'Taylor Swift', birthday: 'December 13, 1989', hometown: 'Reading, PA', favoriteColor: 'red' });

Next let’s define a collection and let’s add those models to the collection…

var Artists = Backbone.Collection.extend({
    model: Artist
});

var artistArray = [biggie, mike, taylor];
var artists = new Artists(artistArray);  

Note: If you are not familiar with models and collections, it will definitely be worth your while to read the sections on Backbone.js Models, Backbone.js Collections. And if you haven’t yet, you may as well read the entry on Backbone.js Views while you’re at as this will also be helpful in understanding this section.

Now that we have our collection of models in it, did you know that we can loop the collection over it using templates? Well, as it turns out, we can! How do we do this? Let’s create a template…

<script type="text/template" id="artist-list-template">
<table>
  <thead>
    <tr>
      <th>Name</th>
	  <th>Hometown</th>
	  <th>Favorite Color</th>
    </tr>
  </thead>
  <tbody>
    <% _.each(artists, function(artist) { %>
      <tr>
        <td><%= artist.get('name') %></td>
        <td><%= artist.get('hometown') %></td>
        <td><%= artist.get('favoriteColor') %></td>
      </tr>
    <% }); %>
  </tbody>
</table>
</script>

That’s pretty neat. Underscore uses the <% %> tags (known as bee sting syntax) to specify templates. The <%= %> specification with the equals sign means we want to evaluate and render the value out to the browser window. If we need to escape HTML in our value we can use <%- %> instead. The tags without these definitions are used for things life if-else conditions and loops. Here we can see we are looping over all of the items in our collection and using the get method for each model to get the data we’re looking for.

Now we can actually pass this into Underscore’s template function. We use the “models” property for a Backbone.js collection to access each model in the Collection as an array…

var template = _.template($('#artist-list-template').html(), {artists: artists.models});
$(".content").html(template);

The rendered content will be injected into a div with the “content” class.

Most of the time when you’re developing a Backbone application, you’re going to be using a view in Backbone.js to do the rendering…

var ArtistListView = Backbone.View.extend({
    el: '.content',
    
    initialize:function(){
        this.render();
    },
    render: function () {
        var template = _.template($('#artist-list-template').html(), {artists: artists.models});
        this.$el.html(template);
    }
});
var artistListView = new ArtistListView();

Handlebars

The Underscore templating engine is a fine solution for your Backbone applications. However, when it comes to templating syntaxes, some people prefer other options. Apart from the default Underscore templating system, one of the more popular templating engines used with Backbone.js applications is the Handlebars templating engine. Handlebars uses the popular mustache style syntax which involves the use of {{ brackets }} to indicate dynamic values.

So the following implementation shows the same thing that we did above, only this time we’re loading up Handlebars and using it to render the dynamic content for our application…

<!DOCTYPE html>
<html>
<head>
<title>Backbone Application</title>
<script src="js/jquery.js" type="text/javascript"></script> 
<script src="js/underscore.js" type="text/javascript"></script> 
<script src="js/backbone.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">

<table>
  <thead>
    <tr>
      <th>Name</th>
	  <th>Hometown</th>
	  <th>Favorite Color</th>
    </tr>
  </thead>
  <tbody>
      {{#each []}}
	  <tr>
	      <td>{{this.name}}</td>
	      <td>{{this.hometown}}</td>
	      <td>{{this.favoriteColor}}</td>
	  </tr>
	  {{/each}}
  </tbody>
</table>
</script>

</script>
 
 
<script type="text/javascript">

var Artist = Backbone.Model.extend({

    defaults:{
        name: 'New Artist',
        birthday: 'January 1, 1970',
        hometown: 'Los Angeles, CA',
        favoriteColor: 'blue',
    },

    initialize: function() {
        console.log('New artist created...');
    }

});

var biggie = new Artist({ id: 1, name: 'Notorious BIG', birthday: 'May 21, 1972', hometown: 'Brooklyn, NY', favoriteColor: 'green' });
var mike = new Artist({ id: 2, name: 'Mike Jones', birthday: 'January 6, 1981', hometown: 'Houston, TX', favoriteColor: 'blue' });
var taylor = new Artist({ id: 3, name: 'Taylor Swift', birthday: 'December 13, 1989', hometown: 'Reading, PA', favoriteColor: 'red' });

var Artists = Backbone.Collection.extend({

    model: Artist,

    initialize: function() {
        console.log('New collection initialized...');
    }
});  

var artistArray = [biggie, mike, taylor];
var artists = new Artists(artistArray);  


var ArtistListView = Backbone.View.extend({
    el: '.content',

    initialize:function(){
        this.render();
    },
    render: function () {
        var source = $('#artist-list-template').html();
        var template = Handlebars.compile(source);
        var html = template(artists.toJSON());
        this.$el.html(html);
    }
});

var artistListView = new ArtistListView();

</script>
</body>
</html> 

As you can see we’ve loaded up Handlebars and the utilized it in the view’s render function. In my humble personal opinion the template looks a lot cleaner in this second version. There are many other templating engines out there to choose from, you’ll just have to pick the one that’s right for you.

Thus concludes our brief introduction into what templating is and how you can use it in Backbone.js. There are many templating tools and libraries out there that you can use to make your Backbone applications more efficient, clean, reusable, and scalable.

]]>
https://9bitstudios.com/2013/05/using-templates-in-backbone-js/feed/ 5