简体   繁体   中英

Using #each to display some data in handlebars.js not displaying

Hi have a project where i'm converting a static website into a datadriven one, for now i am just trying to change so the content of each page is taken into the website through a data object.

I'm using : node.js, handlebars, express

My index.js file has an object like this

var item = [{
  pagetitle: 'Page 1',
  text: 'content page 1'
}, {
  pagetitle: 'Page 2',
  text: 'content page 2'
}, {
  pagetitle: 'Page 3',
  text: 'content page 3'
}, {
  pagetitle: 'Page 4',
  text: 'content page 4'
}, {
  pagetitle: 'Page 10',
  text: 'content page 10'
}];

my index.hbs looks like this

<div class="bb-blah">
  {{title}
  {{#each item}}
  <div class="bb-item" id="item{{@key}}">
     <h2>{{pagetitle}}</h2>
     <div class="cols-2">
         <p>{{text}}</p>
     </div>
  </div>
  {{/each}}
</div>

For some reason nothing is displayed on the page like it should be. "item" should iterate item1 item2 item3 to display each page of the website so i need that to increment every time i press my button (this works on the normal website but i can't get it to work with @key. Also the {{pagetitle}} and {{text}} do not display at all on the website.

It looks like you need to specify what the item property is on the object that you are passing to the template in order for the template to iterate over the items in the item array.

When you are rendering the template, pass in the item array under the property of item . In doing so, your template will see the item property and it will iterate over the items as expected.

var template = Handlebars.compile(html);
var rendered = template({
  item: item
});

The reason there was likely some confusion was because you probably expected the handlebars template to render the item variable, despite not being a property on the object that was passed in.

Here is a basic example demonstrating this:

 var html = $("#template").html(); var template = Handlebars.compile(html); var item = [{pagetitle : 'Page 1', text:'content page 1'}, {pagetitle : 'Page 2', text:'content page 2'}, {pagetitle : 'Page 3', text:'content page 3'}, {pagetitle : 'Page 4', text:'content page 4'}, {pagetitle : 'Page 10', text:'content page 10'}]; $('body').append(template({item: item}));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.6/handlebars.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script id="template" type="text/x-handlebars-template"> {{#each item}} <div class="bb-item" id="item{{@key}}"> <h2>{{pagetitle}}</h2> <div class="cols-2"> <p>{{text}}</p> </div> </div> {{/each}} </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM