Troubleshooting issue: Looping through array in Node.js with Express, JSON, and Handlebars not functioning correctly with

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?

Answer №1

Make sure to use {{this}} when iterating through an array to access the current value.

{{#each artistArtwork}}
   <div class="PICSHERE">
      <img src="images/artwork/{{this}}" alt="">
   </div>
{{/each}}

The mistake you made was trying to access the property artistArtwork from the same array artistArtwork, which caused an error.


Here is a working demo:

let data = {
  "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"]
    }
  ]
};

let artistTemplate = `{{#each artistArtwork}}
   <div class="PICSHERE">
      <img src="images/artwork/{{this}}" alt="">
   </div>
{{/each}}`;

let template = Handlebars.compile(artistTemplate);
console.log(template({ artistArtwork: data.artists[0].artwork }));
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.8/handlebars.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The <mat-radio-button> component does not have a value accessor specified

When working with HTML and Angular, I encountered the following issue: <mat-radio-group> <mat-radio-button [(ngModel)]="searchType"> And (Narrower search) </mat-radio-button> <mat-radio-button [(ngModel)]="searchType"&g ...

Cross-origin resource sharing is not successful when it lacks the HTTP ok status

Working with NodeJS Express on the Zeit Now 2 platform has presented some challenges. Due to CORS issues, I cannot use server.js as a proxy to send data from the backend. Testing on various browsers including Chrome, Safari, and Firefox on desktop, as well ...

Issue with FileStreamResult not triggering download prompt after AJAX call in MVC

I am encountering an issue with my code that is triggered by the "export" li tag. It converts a FusionChart to an SVG string and then sends it to my controller via an ajax call. The problem I'm facing is that even though the controller receives the r ...

The Ionic framework has a defined variable

In my code, I have initialized a variable inside the constructor like this: constructor(public http: HttpClient) { this.data = null; this.http.get(this.url).subscribe((datas: any) => { this.dbUrl = datas[0].db_url2; console.log(this ...

Is there a way to prevent a form from automatically submitting once all inputs have been completed? (Using react-hook-form)

After creating a multi-step-form using shadcn, next, zod, and react-hook-form, I encountered an issue where the form is being submitted on step 3 instead of when clicking the submit button. form.tsx const form = useForm<Inputs>({ resolve ...

How can I remove a row from a JavaScript array based on the value of the first item in the row?

Creating an array in JavaScript can be done like this: var myArray = new Array(); myArray.push({ url: urlValue, filename: fileNameValue }); As time goes on, the array will accumulate various items. If you need to delete a specific row based on the urlVal ...

Tips for building a dynamic navigation menu using AngularJS

Looking to dynamically generate a navigation menu using an angularjs controller: index.html: <body> <div ng-controller="navi"> <ul> <li ng-repeat="nav in navigations"> <a href="{{nav.path ...

Dealing with an Incorrect Date in JavaScript

After working on a JavaScript logic to extract date and time from certain values, I realized that my approach needed some adjustments. Initially, I parsed the DateTime and converted it to a string. Then, I split the string to retrieve the date component. ...

Determine the status of a script in PHP by incorporating AJAX

I am having trouble with my file upload page in the application. I want to display "Uploading" while the file is uploading and then show "Processing" while the file is being processed. Eventually, after the script completes, my page should redirect to a sp ...

Displaying a dynamic progress bar across all elements in fullscreen mode

I am looking to implement a full-screen indeterminate progress bar that overlays all screen elements. Here is my specific use case: When a user fills out a form, including an email field, the email id is checked against a database via ajax. While waiting ...

Error encountered in AngularJS and JSON server: [$injector:unpr] An unidentified provider was found: $resourceProvider <- $resource <- menuFactory

Hello everyone, I recently created a small AngularJS application and utilized a JSON server for my backend operations. Unfortunately, I am encountering an issue with the provider in my code. Upon running it, I am receiving errors as shown below: Uncaugh ...

Struggling with Passport.js authentication on a Vue.js live-reload server and Node server in a development environment

UPDATE: I'm encountering an issue with my Vue frontend not setting the session cookie Objective: To enable Login with Twitch and establish synchronized authenticated sessions between the frontend and backend systems Description: I am facing diffic ...

displaying 'undefined' upon completion of iterating through a JSON file using $.each

For my project, I am attempting to extract only the date data from a JSON object. I have successfully looped through the object and displayed it, but the issue arises at the end of the loop where it shows undefined. I am not sure what mistake I am making. ...

Skipping a JSON field in HTML/JavaScript when it is blank: A guide for developers

To develop an interactive program based on JSON input, I aim to display headers, subheaders, and choices derived from the JSON data. Some input fields may remain unfilled. For instance: Header Subheader Choice 1 Choice 2 Subheader2 Choice ...

Get started with the free plan for sails.js on Paas

Looking to test out my sails.js application deployment options. Can't seem to find sails.js on the supported list for Heroku and OpenShift's node.js offerings. Are there any free Platform as a Service (PaaS) plans available for sails.js? ...

Utilizing Angular's ng-repeat with varying directives for each iteration

I am trying to utilize ng-repeat within Angular to iterate through multiple <li> elements with a directive embedded. My goal is to have the first two items in the ng-repeat display differently in terms of styling and content compared to the remaining ...

When it comes to HTML and Javascript drawing, getting the positioning just right can be a challenge

I'm currently developing a control website for a drawing robot as part of a school project. However, I've been facing some challenges with the functionality of the drawing feature. Though I admit that the site lacks attention to detail, my main ...

What is the process for modifying the logfile path in phantomjs using selenium?

Is there a way to modify the default --webdriver-logfile parameter that selenium passes to phantomjs when using them together? This is the line in the selenium log: 11:06:06.960 INFO - arguments: [--webdriver=14380, --webdriver-logfile=<ROOT PATH DELE ...

Modify Javascript to exclusively focus on SVG paths

I successfully created an SVG animation using JSFiddle, but when I transferred the SVG to Shopify, the Javascript that animates the path stopped working. It seems like the issue is with the JavaScript targeting all paths on the page instead of just the sp ...

streamlined method for accessing page parameters in nested components using the next.js application router

In my next.js application, I have a deep hierarchy of nested components. I currently use the params.lang parameter for translations, but I find myself passing it down to every nested component. Although there are hooks available, I prefer rendering them ...