Updating the home controller

If you take a look at our current home controller (controllers/home.js), you can see that the index function barely has any code in it whatsoever:

res.render('index');

The first thing we want to do is build a basic View model using sample data so that we can see our View model at work. Replace that single res.render call with the following updated code:

const ViewModel = {
images: [
images: [{
uniqueId: 1,
title: 'Sample Image 1',
description: '',
filename: 'sample1.jpg',
Views: 0,
likes: 0,
timestamp: Date.now()
}, {
uniqueId: 2,
title: 'Sample Image 2',
description: '',
filename: 'sample2.jpg',
Views: 0,
likes: 0,
timestamp: Date.now()
}, {
uniqueId: 3,
title: 'Sample Image 3',
description: '',
filename: 'sample3.jpg',
Views: 0,
likes: 0,
timestamp: Date.now()
}, {
uniqueId: 4,
title: 'Sample Image 4',
description: '',
filename: 'sample4.jpg',
Views: 0,
likes: 0,
timestamp: Date.now()
}]
};
res.render('index', ViewModel);

In the preceding code, we built a basic JavaScript collection of objects. The constant we declared is called ViewModel, but the name of this constant doesn't actually matter and can be whatever you want. The const ViewModel is an object that contains a single property called images, which is in itself an array.

The images array contains four sample images, each with a few basic properties--the most obvious properties were decided when deciding what kind of information we wanted per image. Each image in the collection has a uniqueId, title, description, filename, Views, likes count, and a timestamp property.

Once we set up our ViewModel, we simply pass it as the second parameter to the res.render call. Doing this while rendering a View makes the data in it available to the View itself. Now, if you recall from some of the template code we wrote for the home index.Handlebars View, we had a {{#each images}} loop that iterated through each image in the image collection of the View model passed to the template. Taking another look at our View model we created, we see that it only has a single property named images. The HTML code inside the Handlebars loop will then specifically reference the uniqueId, filename, and title properties for each image in the images array.

Save the changes to the home controller, launch your app again, and navigate to http://localhost:3300. You should see the four images that now appear on the home page in the Newest Images section (although, as you can see in the following screenshot, the images are still broken, as we didn't actually create any image files):

The home page has a fairly simple controller and View model, and you might have noted that the sidebar is still completely empty. We'll cover the sidebar a little later in this chapter.

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

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