Passing data from server to a handlebars view

In this tutorial, we’re going to set up a node server, create some express handlebars views, and pass data from the server to these templates. In a real-life scenario, this data would most likely be fetched from a database. But we’ll not get into that in this tutorial. This is just to show you how handlebars views can be set up quickly and accept data from a server.

Initial Set up

Start by creating a project folder. Name it whatever you like, I called mine pass-data-to-handlebars. Launch your command terminal and go to the folder you created. I use Visual Studio Code‘s inline command terminal (which can be launched using Ctrl + `) when working on a NodeJS project. I just think it’s convenient. You may use a terminal of your choice. In your command terminal type

npm init

 

 

image of npm init prompts

You will be presented with a series of prompts. For now, just accept the defaults (hit Enter key through all prompts). You can modify these values in a file called package.json that will be created once this command has run successfully.

Next, let’s install express and nodemon. You can do this by running the following commands in the terminal

npm install express --save

npm install nodemon --save-dev

express will be used to set up a server. nodemon will watch server files for any changes and will automatically restart the server whenever these are saved – so that we don’t have to do it. Since nodemon is required only for development and is not an essential component of our project we append dev to its command. This means that it will be installed as a dev dependency. Once the commands have run successfully, you should see a node_modules folder in your project folder. This is where all your installed packages and their dependencies are saved. Next, let’s set up our server.

 

Setting up a Server

Create a file called index.js (the filename should be the same as the value of main in package.json). In index.js, add the following code to it.

var express = require('express'),

    http=require('http'),

    app=express();

//set port
app.set('port', process.env.PORT || 3000);

app.get('/', function(req, res){

    res.send('you should see this, if everything is set up correctly');

});

//start server
http.createServer(app).listen(app.get('port'), function () {

    console.log('Great things are anchored at port '+app.get('port'));

});

 

This is a basic server setup.

  • Required express and http
  • Created an express instance called app.
  • Set ‘port’ value to 3000.
  • Defined what happens on a GET request to our root (‘/’).
  • Created a server at ‘port’

In your terminal, type nodemon and hit Enter. nodemon will now watch all server-side files and restart the server whenever you make any changes.

Launch localhost:3000 in a browser. You should see the text that we specified in res.send. Our server is now up and running.

Configure Handlebars

Let’s move on to the main task and install express-handlebars. Run the command

npm install express-handlebars --save

 

Once installed, require express-handlebars in your index.js file, like so

var express = require('express'),

    http=require('http'),

    exphbs = require('express-handlebars'),

    app=express();

 

Before we can use handlebars as templates we need to configure it. Include the following code in your index.js

//set view engine

app.engine('.hbs', exphbs({

    defaultLayout:'default', //specifying the file name of our default template

    layoutsDir:"views/layouts/", //specifying the directory where layouts are saved

    extname:'.hbs' //defining file extension. if not specified, the default is 'handlebars'

}));

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

 

Update your folder structure to look like this

.
|
|--views
|  |--layouts
|  |  |--default.hbs
|  |--main
|  |  |--index.hbs

In our handlebars configuration, we have specified default.hbs as the defaultLayout (note that the extension is not required when mentioning the file name). A default layout, in this case, is the HTML structure inside which our views will be injected.

image explaining default layout

Add the following HTML to default.hbs

<!DOCTYPE html>

<html lang="en">

    <head>

        <title>Data to handlebars</title>

    </head>

    <body>

        {{{body}}}

    </body>

</html>

 

What we’ve done here is defined the structure of all our pages. Anything that needs to change on a page will go in {{{body}}}. To pass a view inside {{{body}}}, go back to your index.js file and replace res.send  with res.render(‘main/index’)

app.get('/', function(req, res){

    res.render('main/index');

});

 

Now, whenever you go to the path ‘/’, the contents of ‘main/index’ will be injected in {{{body}}} and should be visible on the screen. Test it out by adding some dummy text in ‘main/index’ and refreshing localhost:3000.

Next step is passing data to our view. And now that we have everything in place, doing that is as easy as

app.get('/', function(req, res){

    var data='Hello from server';

    res.render('main/index', {

        data

    });

});

 

To receive and display this data inside your view, use the same variable name you passed in res.render. In you ‘main/index.hbs’ include

{{data}}

 

If you refresh localhost:3000, you should see ‘Hello from server’. And that’s it. That’s how easy it is to pass data to a handlebars view.

Next Step

Instead of passing a string, try passing an object (e.g. data = {prop1: ‘objprop1’, prop2: ‘objprop2′}. In your view, you’ll need to access it using data.prop1 or data.prop2. You can also try passing an array and populate it using handlebars’ helpers like each.

Conclusion

In this tutorial, we learned how to configure express-handlebars for our project and then pass data from the server to a view. express-handlebars comes with useful helpers like each and if that can be used to display, modify, validate data in your view. It also lets you create custom helpers.

Documentation for express-handlebars

Leave a Reply

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