Troubleshooting a problem with handlebar's simple nested forEach loop

This is a snippet of code related to node.js:

   app.get('/payees', function(req, res)
   {
     var categoriesPromise = Category.getAllCategories();
     var payeesWhereNullPromise = categoriesPromise.then(function() {
        return Payee.getAllPayeesWhere({categoryId:null})
    })
    payeesWhereNullPromise.then(function(payees) {
        var categories = categoriesPromise.value();
        res.render('payees', {categories: categories, subcategories: [], payees:payees});
    })
});

This code snippet is used on the front end side:

{{#each payees as |payee|}}
    {{#each categories as |category|}}
            category.name
    {{/each}}
{{/each}}

Although these codes work perfectly when executed separately, combining them does not produce the desired result.

Answer №1

While using the #each in Handlebars, you can only access the properties of the array being looped through. In your example, the issue arises with the nested foreach where Handlebars attempts to find categories as an object property within the payees array. However, since categories is actually a global variable in your case, it cannot be found.

To achieve what you desire, you can utilize a Handlebars helper function.

UPDATE: Below is an illustration of how to use a handlebar helper function.

Template:

 {{#list categories payees}}{{/list}}

Node server code:

var hbs = require('hbs');
hbs.registerHelper('list', function(categories, payees, options) {
   var out = "";
   // Implement standard JavaScript here for customization.
   // Nested loops are also supported.
   // Assign the desired HTML to the out variable for rendering 
   // in your template.
   for (var i = 0; i < categories.length; i++) {
      out += "<div>"+categories[i]+"</div>";
      for (var j = 0; j < payees.length; j++) {
      // Continue as needed
      }
   }
   return out;
});

Documentation: https://github.com/pillarjs/hbs http://handlebarsjs.com/

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

What is the best way to have a form open upwards when hovered over or clicked on?

Attempting to create a button in the bottom right corner that will reveal a form when clicked or hovered over. The form should slide open slowly and close after clicking on login, but currently the button is moving down as the form opens. The button also ...

What is the best way to convert exponential values to decimals when parsing JSON data?

var value = '{"total":2.47E-7}' var result = JSON.parse(value); Looking to convert an exponential value into decimal using JavaScript - any suggestions? ...

Utilize JavaScript to submit the FORM and initiate the 'submit' Event

Hey there! Here's the code I've been working on: HTML : <html> <body> <form enctype="multipart/form-data" method="post" name="image"> <input onchange="test();" ...

The "smiley" character added to the information during an Ajax call

Encountering an unusual issue. A colon (:) character is being appended to the JSON data sent to the server via AJAX request. https://example.com/image1.png The colon character seems to appear after sending the JSON, but it does not show up when inspectin ...

Why am I encountering this export issue while attempting to integrate a NextAuth.js Provider with Next.js?

Embarking on my first project in React/Next.js, I opted to employ NextAuth.js for authentication. Following the initial steps outlined in the Getting Started guide provided by NextAuth, I have successfully set up a [...nextauth].js page featuring the code ...

Refresh the Vuex store using the main process of Electron

Is there a way to update a vuex store by committing changes from the main process? Here is an example: In the main thread: import store from '../store' ipc.on('someevent', (event, args) => { // do something with args store ...

What is the best way to add content to the nearest div with a specific class?

I'm attempting to use jQuery to identify and wrap images within text, then relocate them to another div. However, I am encountering difficulties getting it to function as intended. Below is the code that I have so far that appears to be effective: $ ...

The Ajax request returned a status of 200, yet an error message was displayed

Even though the status is 200, why does it print the error message inside alert("error...");? function makeSelect() { var blouseoption = document.querySelector('input[name="blouseoption"]:checked').value; var url = "http://dukano.co/sakh ...

Using the base tag in Angular HTML5 mode can cause script links to break

Issue Following the configuration of a base tag to enable Angular 1.x in HTML5 mode, encountering an error where the browser (Chrome) sends requests to an incorrect path for scripts when directly accessing the app via localhost:3000/resource/id. Specific ...

How can I extract the URL from the event listener in Cordova's in-app browser event and then automatically close it once a specific URL is reached?

In my journey with ionic version 1 (just starting out with ionic & angularjs), I encountered an issue while trying to close the in app browser upon reaching a specific URL. The problem arises from the fact that the event triggered on "loadstart" is o ...

Angular version 7.2.1 encounters an ES6 class ReferenceError when attempting to access 'X' before it has been initialized

I have encountered an issue with my TypeScript class: export class Vehicule extends TrackableEntity { vehiculeId: number; constructor() { super(); return super.proxify(this); } } The target for my TypeScript in tsconfig.json is set to es6: ...

Steps for downloading a file using Selenium in Python while invoking ng-clickWant to learn how to

Attempting to download a file from a website using Selenium Python by clicking a button defined with ng-click. The HTML file contains the following code: <div class="col-lg-6 btn-group"> <br/> <br/> <input type="button" ng-clic ...

Extracting data from a Wikipedia table using web scraping in JavaScript

I'm attempting to extract information from a specific website. <script> var convertToInt; var allData = []; $.ajax({ url: "http://en.wikipedia.org/wiki/Demographics_of_Europe", type: 'GET', cache: false, success: func ...

Postponing the activation of toggleClass in jQuery until the completion of a slide animation

Having some trouble with the jQuery delay() function. I'm using it to pause a toggleClass action until after a slideUp animation on one of my divs, but it doesn't seem to be working as expected. I want a bar with rounded corners that expands whe ...

Type 'function that accepts an argument of type User and TypedAction<"login start"> and returns void'

I recently started learning TypeScript and I'm delving into state management in Angular 11. However, when I try to create an effect, I encounter an error stating Argument of type '(action: User & TypedAction<"login start">) => void' ...

Can an entire object be bound to a model in an Angular controller function?

In TypeScript, I have defined the following Interface: interface Person { Id: number; FirstName: string; LastName: string; Age: number; } Within a .html partial file, there is an Angular directive ng-submit="submit()" on a form element. A ...

Tips for delivering a temporary piece of HTML and JavaScript to a live application using Node.js

After successfully getting my first app running on Node.js, it is currently serving a static file. I have some exciting ideas in mind for future implementation, so I'm setting up Node to be prepared when the time comes. // require modules var express ...

encountered issue accessing optional property post validation check

flow 0.67.1 (although behavior still present in version 0.73.1) For Instance: type PropOptional = { prop?: ComplexType }; type ComplexType = { callable: () => void, anotherCallable: () => void }; function usePropOpt ...

Is there a way to prevent a link from activating when I click on one of its internal elements?

Within a div nested inside an "a" tag (specifically in Link within next.js), there is another div labeled as "like." When clicking anywhere within the main div, the intention is for it to redirect to the destination specified by the "a" tag. However, if th ...

Navigational mapping tool with interactive user interface

I'm currently utilizing geomap to visualize the location using the following code snippet: function OnLoad() { $.ajax({ type: "POST", **url: "CS.aspx/CreateWorldMap"**, data: '{}', ...