Handlebars.js iterating over for loop using Handle without losing data

久未见 提交于 2019-12-13 03:54:39

问题


I'm trying to iterate over "for" loop using Handlebars.js, but inside the loop, I cannot retrieve data passed to the template. Here is how I tried:

For the loop function:

Handlebars.registerHelper('for', function (from, to, incr, block) {
  var accum = '';
  for (var i = from; i < to; i += incr)
    accum += block.fn(i);
  return accum;
});

Template file:

{{#for 0 10 2}}
 <tr>
  <td class="p-0">
   <input class="form-control" data-position="B5_{{id}}_{{B5.id}}" type="text" {{#if B5.isReadOnly}} readonly {{/if}} value="{{B5.value}}"/>
  </td>
 </tr>
{{/for}}

Inside the loop, I cannot retrieve {{id}} or {{B5.id}}, which normally works outside.

Here is how I pass data to the template:

 export function renderSheet(template, data) {
      try {
        return Handlebars.compile(template)(data);
      } catch (e) {
        console.error(e);
        return null;
      }
    }

Please help me figure out what is wrong here. I'd be appreciated.

UPDATE Thank a comment, I have now can access data inside the loop, but I got another problem which is how do I get current "i" value inside the for loop?. For example:

{{#each @root.A5.value}}

How can I replace 5 with current i value?

来源:https://stackoverflow.com/questions/55567260/handlebars-js-iterating-over-for-loop-using-handle-without-losing-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!