I have a precompiled handlebars template and I would like to pass a variable containing a number into Handlebars.template.foo(bar). So it would look something like Handlebars.template.foo(bar, 1).
I would then like to be able to access that number so that I can pass it into my helper. so I would like to do
{{myHelper bar num}}
{{something}}
{{myHelper}}
I have the helper set up ready to receive the number and it does if I invoke {{myHelper bar 1}}, but its passing the number from the original javascript into the variable 'num' I am having trouble with.
here is my helper by request :
Handlebars.registerHelper('myHelper', function(bar, num){
var ret = ""
for(var i=0; i < bar.length; i++){
if(bar[i].id == num)
ret = ret + bar[i]
}
return ret;
});
If you could please let me know if this is first of all possible and secondly how to do it.
thanks in advance.
Im not completely sure of what your issue is. But from what I understand you are trying to create a block helper like the built in 'each'.
If that's the case, your usage is wrong. Block helpers need to start with #
and it ends with a /
. So you helper would be used like
{{#myHelper items num}}
{{something}}
{{/myHelper}}
If you want to dynamically look up a property inside the block helper, you will need to pass the context object to the function inside the options argument. Your helper will look like
Handlebars.registerHelper('myHelper', function(items, num, options){
var ret = ""
for(var i=0; i < items.length; i++){
if(items[i].id === num) {
ret = ret + options.fn(items[i]);
}
}
return ret;
});
To test out this helper I created a sample object like
{
items: [{id: 1, something:'First Item'},
{id: 2, something:'Second Item'},
{id: 3, something:'Third Item'}
],
num: 3
}
You can try this helper at the tryhandlbars and see if this is what you need.