I'm struggling to grasp the concept of looping through an object in Handlebars and transferring information from one location to another.
Here is a sample json file that I am attempting to read from. The file, named "testdata.json", contains:
{
"artists":
[
{
"name": "person 1",
"artwork": ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg"]
},
{
"name": "person 2",
"artwork": ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg"]
},
{
"name": "person 3",
"artwork": ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg"]
},
{
"name": "person 4",
"artwork": ["pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg"]
}
]
}
In my app.js file, I import this data into a variable called testdata
.
const testdata = require('./data/testdata.json');
Then, I pass it along with "app" to my homepage route file using the code below:
homepageRoute(app, testdata);
My goal is to extract the array containing image filenames from testdata, transfer it to the homepage (index.hbs) via a route, and then utilize Handlebars to iterate over the array and create a small image gallery.
This is what my sample routes file for the homepage looks like:
module.exports = function homepageRoute(app, testdata){
app.get('/', function(request, response){
var TestWholeArray = testdata.artists[0].artwork;
response.render('index', {
pageTitle : "Home Page",
pageId : "home",
artistArtwork : TestWholeArray
});
});
}
However, when I implement the following in index:
Handlebars in index:
{{#each artistArtwork}}
<div class="PICSHERE">
<img src="images/artwork/{{artistArtwork}}" alt="">
</div>
{{/each}}
The images do not appear. Upon inspecting the backend code through the console, I see the following output:
<div class="PICSHERE"><img src="images/artwork/"" alt=""></div>
<div class="PICSHERE"><img src="images/artwork/"" alt=""></div>
<div class="PICSHERE"><img src="images/artwork/"" alt=""></div>
<div class="PICSHERE"><img src="images/artwork/"" alt=""></div>
The filename does not display. When I attempt to console.log(TestWholeArray );
in terminal, I can see the array as expected:
[ 'pic1.jpg',
'pic2.jpg',
'pic3.jpg',
'pic4.jpg' ]
To simplify the testing further, if instead of using:
var TestWholeArray = testdata.artists[0].artwork;
I delve deeper into the array to retrieve just one image by using:
var TestWholeArray = testdata.artists[0].artwork[0];
It works with the single image showing up. The issue arises when trying to include multiple images.
What could be missing or where am I going wrong?