01 Project – Node.js / Express / MongoDB – Part 11 – Rendering the views

None of these views we have created so far will do anything unless we make a few modifications to our controllers to get our views to render properly.

Open /controllers/home.js and update the contents to look identical to the code shown below:

module.exports = {
  index: function(req, res) {
    res.render('index');
  }
};

Instead of performing res.send, which just sends a simple response, we are calling res.render and passing in the name of the template file we want to render as the only parameter (for now). The index file will be loaded from our views folder.

Let’s update the image controller to do the same thing as well. Edit /controllers/image.js and change the index function to look as the code below:

index: function(req, res) {
    res.render('image');
  },

Before visualizing in the terminal what we have done, we need to define the view engine. Open the index.js file and add the following line of code:

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

Now, the whole index.js file looks like it is shown below:

var express = require('express');
  config = require('./server/configure'),
  app = express();
app.set('port', process.env.PORT || 3300);
app.set('view engine', 'handlebars');
app.set('views', __dirname + '/views');
app = config(app);

//app.get('/', function(req, res) {
//  res.send('There is nothing to show yet');
//});

var server = app.listen(app.get('port'), function() {
  console.log('Server up: http://localhost: ' + app.get('port'));
});

Now, let’s see how it looks in the browser. Start the server by running the node index command in the terminal. Go visit http://localhost:3300 then visit http://localhost:3300/images/an_image.

Rendering the views

Rendering the views

Leave a Reply