Displaying an image

The index function in the image controller will look almost identical to the index function from the home controller. The only difference is that instead of generating an array of images, we will build a ViewModel for a single image. However, the ViewModel for this image will have a little more information than the one from the home page since we are building a page that renders a more detailed view of an image (versus the thumbnail collection on the home page). The most noteworthy inclusion is that of a comments array for the image.

Taking another look at the original index function in our controllers/image.js file, we can see the simple existing res.render line of code:

res.render('image');

We want to replace this line with a ViewModel and an updated res.render statement using the following code:

const ViewModel = {
image: {
uniqueId: 1,
title: 'Sample Image 1',
description: 'This is a sample.',
filename: 'sample1.jpg',
Views: 0,
likes: 0,
timestamp: Date.now()
},
comments: [{
image_id: 1,
email: '[email protected]',
name: 'Test Tester',
gravatar: 'http://lorempixel.com/75/75/animals/1',
comment: 'This is a test comment...',
timestamp: Date.now()
}, {
image_id: 1,
email: '[email protected]',
name: 'Test Tester',
gravatar: 'http://lorempixel.com/75/75/animals/2',
comment: 'Another followup comment!',
timestamp: Date.now()
}]
};
res.render('image', ViewModel);

Here, we declare a new ViewModel constant again--this time with an image property that contains the properties for the single image. In addition to the image property, there is also a comments property, which is an array of comment objects. You can see that each comment has various properties specific to a comment for each image. This JavaScript object is actually a pretty good preview of what our real data will wind up looking like once we include logic to connect our app to MongoDB.

After we build our sample image object and its collection of comments, we pass that to our res.render call, thus sending this new ViewModel directly to our image's Handlebars template. Again, if you review the HTML code in the image.Handlebars file, you can see where each property of the ViewModel is being displayed.

Again, let's run the application and make sure that our image page appears properly:

$ node server.js

Once the app is running and you've launched it in your browser, click on any of the images that are listed in the Newest Images section of the home page.

This should take you to an individual image page where you will see something like the page shown in the following screenshot:

Note that Title, Description, Likes, Views, and timestamp (converted to a different format for user readability) are all now appearing on the page. In addition, you can see a few comments listed near the image as well!

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

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