Search code examples
javascriptexpresshandlebars.js

Simple Nested handlebar foeach doesnt work


This is in node.

   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 is in the front end

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

If I do them seperately they work perfectly but the moment I place them inside each other nothing happens.


Solution

  • You can only access the properties of the array you're looping through within #each. With the nested foreach in your example you have the problem that Handlebars tries to find categories as object property in the payees array. But in your case categories is a global variable and therefore won't be found.

    But you can do what you want with a Handlebars helper function.

    EDIT: Here an example of using 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 = "";
       // Here you can use standard JavaScript to do whatever you want.
       // Also nested loops are possible.
       // Put the wished HTML into the out variable and it will get rendered 
       // in your template.
       for (var i = 0; i < categories.length; i++) {
          out += "<div>"+categories[i]+"</div>";
          for (var j = 0; j < payees.length; j++) {
          // and so on
          }
       }
       return out;
    });
    

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