Getting Started With Express 4.x View – Template Engine – Tutorial 3

In this blog post we will look into express “views” and how to apply different template engines.

In the previous blog post we saw what are routes in express and how to use basic routing.
If we take the code which we saw earlier,

router.get('/', function(req, res) {
  res.render('index', { title: 'Express' });
});

Here in the render function, ‘index’ is the name of view file and ‘title’ is an variable which are passing to the view to be rendered.

What is Express Template Engine and Why do we need them

If you have developed any web application in the past (taking e.g of PHP as scripting language), there are few important things which are needed in our view logic.

1. Able to modularize html code and include it in different layout: Usually in an web app, we have a header.php, footer.php, head.php, left.php, content.php and the main layout.php files. We reuse these different template files through the application. Since express is only html/javascript, we need a template engine to be able to modularize our html code and reuse it across different layouts.

2. Basic Conditional Statements and Iteration/Loops are required to render data: We always require if conditions, for loop in our view logic to display data. Pure html doesn’t have these, so we need a way to be able to put these using javascript. This is where template engine comes into picture.

3. One of the most basic uses of template engine is to pass data from any data source e.g database to frontend view and able to display it. Pure HTML is a static markup language, we need additional power in our templates to be able make dynamic websites.

There are many nodejs based template engines available like jade, mustache, handlebar etc but i will only discuss a few here.
Jade Engine come pre installed when use express generator. Jade syntax is a simpler but different form of html (which can be seen here http://jade-lang.com/), but since its different from html I do not personally prefer it.
We will see how to use handlebar in express 4.x

Handlebar with Express 4.x

I personally prefer handlebar over mustache, because it has few more extra features which are useful. But both enforce the concept of logicless views, i.e keeping most the logical stuff in javascript files and not templates.
Detailed syntax of handlebar can be found here http://handlebarsjs.com/ for reference.

We are going to use express-handlebar engine

First to install

$ npm install express-handlebars --save

The –save parameter adds dependency to your package.json file, so that you can easily install dependencies in future using single command “npm install”

Next, remove the previous “jade” view engine. Remove the line from app.js

app.set('view engine', 'jade');

and add these lines instead

var exphbs = require('express-handlebars');
app.engine('.hbs', exphbs({defaultLayout: 'single', extname: '.hbs'}));
app.set('view engine', '.hbs');

So above we have set the “.hbs” engine as a view engine. The view file extension would be .hbs and default layout is “single”

Template Engine Concepts: Layouts and Partials

In handlebar, to modularize the code we use layouts and partials.
Layouts act as main html files which contain the skeleton code for your layouts e.g 1column layout, 2column-left, 2column-right, 3column layout etc.
Partials act as smaller code fragments which we reuse through layouts e.g header, footer, head etc

Layout are located at : views/layouts/
Partials are located at : views/partials/

You need to create these folders

Here is example of a layout file

<html>
    {{>head}} //partial definition
    <body>
        <div class="container">
            {{{ body }}}  //body is placed
        </div>
    </body>
</html>

Will discuss above in detail later

Helloworld using Express Handlebars

Lets create a basic helloworld application using handlebars
First remove the existing .jade files from your views folder

We will use bootstrap library for frontend. You can download it from http://getbootstrap.com

Add the javascript/css/font files to public/ folder.
Next need to create a layouts/ and partials/ folder in the views/ folder which will hold our layout and partial files.

We will create a single.hbs file in layout folder

<html>
    {{>head}}
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-12 text-center">
                    {{{ body }}}
                </div>
            </div>
        </div>
    </body>
</html>

It using one head partials the placeholder for body content.

Next we need to define the partials in its folder. Create views/partials/head.hbs and put code as shown here
https://github.com/manishiitg/excellence_magento_blog/blob/master/nodejs/express/tutorial3/views/partials/head.hbs

In our index.js routes file we had

router.get('/', function(req, res) {
  res.render('index');
});

For this we need to create a views/index.hbs file

//index.hbs
Hello Express!!!

Now run the application using

set DEBUG=handle & node .bin/www

and open http://127.0.0.1:3000 on your browser. You will get Hello Express!!! on your browser.

Full Code For this can be found here https://github.com/manishiitg/excellence_magento_blog/tree/master/nodejs/express/tutorial3


Experiment
1. Create a 2column-left layout and a different layout file called 2column-left.hbs and open it in URL http://127.0.0.1:3000/2column
2. Add a partial footer.hbs and include it in all your layouts