2

I am building an app using node.js and am using handlebars for server and client side templating. However, I'm having trouble iterating over an object. Here's my code:

My .js file:

$(function () {
  var theTemplateScript = $("#update_address_distributor_template").html();
  context.city = 'london';
  var theTemplate = Handlebars.compile(theTemplateScript);
  var theCompiledHtml = theTemplate(context);
  $('.update_address_distributor_template_placeholder').html(theCompiledHtml);
});

My html file:

<script id="update_address_distributor_template" type="text/x-handlebars-template">
   <form class="form-horizontal" role="form" id="update_distributor_form">
      \{{city}} //correctly prints out london
      \{{address_distributors.length}} //returns 2, so i know the object exists
      {{#each address_distributors}}
       \{{name}} //does not print anything
      {{/each}}
    </form>
</script>

My context object:

{
    address_distributors: {
        [

            {
                name: 'nike',
                id: '1'
            },

            {
                name: 'yokohama',
                id: '4'
            }

        ]
    },

    city: 'london'

}

My {{#each ../address_distributors}} ... {{/each}} does not print anything. I know my addres_distributors object exits because \\{{address_distributors.length}} prints 2 on the html page. Also, to test that my handlebars template is properly setup, I set context.city = 'london'; to see if it would print out, which it did. So I know the issue has something to do with the object...

Can someone help?

Thanks in advance!

Trung Tran
  • 13,141
  • 42
  • 113
  • 200

2 Answers2

1

There is a problem with your data, I've had a try with the data below :

{ "address_distributors": [ { name: 'nike', id: '1' }, { name: 'yokohama', id: '4' } ], city: 'london' }

I get the following result :

london //correctly prints out london
2 //returns 2, so i know the object exists
nike //does not print anything
yokohama //does not print anything

Here is a fiddle of my test : https://jsfiddle.net/ChristopheThiry/30xh7epu/

Christophe
  • 2,131
  • 2
  • 21
  • 35
0

The name variable does not exists. Try

{{this.name}}

Also, you could simply try

  {{#each address_distributors}}
    Anything // Just to see if your loop works.
  {{/each}}
Cohars
  • 3,822
  • 1
  • 29
  • 50