Christophe Thiry Christophe Thiry - 2 days ago 5
Javascript Question

How to avoid using a .. lookup inside a handlebar helper

I wonder if it is possible to avoid using the .. syntax inside a custom helper.

Let's say that I have this helper :

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


is it possible to use it without having to put .. for references inside it :

{{#for 0 5 1}}
{{#ifCond1OrCond2 (lookup ../bid this) (lookup ../ask this)}}
<tr>
<td>{{math this "+" 1}}</td>
<td>{{#with (lookup ../../bid this)}}{{quantity}}{{/with}}</td>
<td>{{#with (lookup ../../bid this)}}{{price}}{{/with}}</td>
<td>{{#with (lookup ../../ask this)}}{{price}}{{/with}}</td>
<td>{{#with (lookup ../../ask this)}}{{quantity}}{{/with}}</td>
</tr>
{{/ifCond1OrCond2}}
{{/for}}


Here is a fiddle https://jsfiddle.net/ChristopheThiry/f9wu07f4/ that show what is going on

Here is the syntax I'd like to use :

{{#for 0 5 1}}
{{#ifCond1OrCond2 (lookup bid this) (lookup ask this)}}
<tr>
<td>{{math this "+" 1}}</td>
<td>{{#with (lookup bid this)}}{{quantity}}{{/with}}</td>
<td>{{#with (lookup bid this)}}{{price}}{{/with}}</td>
<td>{{#with (lookup ask this)}}{{price}}{{/with}}</td>
<td>{{#with (lookup ask this)}}{{quantity}}{{/with}}</td>
</tr>
{{/ifCond1OrCond2}}
{{/for}}

Answer

I found myself a solution in documentation : using @root does the job as it starts from the root element.

 {{#for 0 5 1}}
        {{#ifCond1OrCond2 (lookup @root/bid this) (lookup ask this)}}
        <tr>
          <td>{{math this "+" 1}}</td>
          <td>{{#with (lookup @root/bid this)}}{{quantity}}{{/with}}</td>
          <td>{{#with (lookup @root/bid this)}}{{price}}{{/with}}</td>
          <td>{{#with (lookup @root/ask this)}}{{price}}{{/with}}</td>
          <td>{{#with (lookup @root/ask this)}}{{quantity}}{{/with}}</td>
        </tr>
      {{/ifCond1OrCond2}}
  {{/for}}
Comments