Rendering the views

Let's take a minute to do a quick recap and see what we've done up to this point. So far, we have done the following:

  • We created index.Handlebars and image.Handlebars, the views for the two main pages of the application
  • We created layouts/main.handelbars, the main layout file for every page in the application
  • We created partials/comments.Handlebars, popular.Handlebars, and stats.Handlebars
  • We created a global timeago Handlebars helper

So far, so good; however, none of these views actually do anything, receive any viewModels, or even appear when you run the application! Let's make a few quick minor modifications to our controllers to get our views to render properly.

Open /controllers/home.js so that you can edit the home controller module.
Update the contents of that file so that it looks identical to the following block of code:

module.exports = { 
    index: (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). Using the defaults that were defined in our configure module, the index file will be loaded from our views folder. Again, also using the defaults, we configured the default layout of main that will be applied to this view in our configure module.

Let's update the image controller to do the same thing as well. Edit /controllers/image.js and change the index function so that it looks identical to the following block of code:

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

And that's it! Let's fire up the server, open the app in our browser, and see how
it looks:

    $ npm start
    $ open http://localhost:3300
    $ open http://localhost:3300/images/1
The preceding command uses npm start to start the application. Please note that this command will work only if you have the application entrypoint file configured in the package.json file. If this is not working, then you have to set the main attribute in the package.json and set it to the server.js file. Also, as an alternative, you can manually invoke the server.js file by using node server.js.

Success! Hopefully, you see something that closely resembles the following screenshot of the home page:

Additionally, if you provide a random URL to a specific image, for example,
http://localhost:3300/images/1, you should see the following screenshot:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.170.134