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:
var viewModel = {
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 this code, we built a basic JavaScript collection of objects. The variable we declare is called viewModel
, but the name of this variable doesn't actually matter and can be whatever you want. The viewModel
variable is an object that contains a single property called images
, which is itself an array. The images
array contains four sample images, each with a few basic properties—the most obvious properties we came up with while deciding what kind of information we want per image. Each image in the collection has a uniqueId
, title
, description
, filename
, views
and likes
count, and a timestamp
property.
Once we have 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 HTML code we wrote for the home index.handlebars
view, we had a {{#each images}}
loop that iterated through each image in the images
collection of the view model passed to the template. Taking another look at our view model we created, 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 point your browser to http://localhost:3300
. You should see the four images that appear on the homepage now 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 may have noticed that the sidebar is still completely empty. We'll cover the sidebar a little later in this chapter.
3.144.35.122