Reputation: 20890
I have a helper called printArray
that just prints every item in an array. It works great when I define the array in JS and pass it in to the helper via a context object. What I want to do is define the array right in the template, like:
{{printArray arr=[1, 3, 4] }}
Unfortunately, by the time this gets to my helper, the arr
key points to undefined
. Is there any valid syntax to get the array inside my helper without defining it in javascript?
Upvotes: 22
Views: 19486
Reputation: 21
Helper:
printArray: (...options) => {
// remove unneeded properties
options.pop();
// return option array
return options;
}
Template:
{{printArray "banana" "apple" "orange" "kiwi"}}
Returns:
["banana", "apple", "orange", "kiwi"]
You can use it in conjunction with other helpers:
{{#each (printArray "banana" "apple" "orange" "kiwi")}}
{{this}}
{{/each}}
Upvotes: 2
Reputation: 1
{{printArray '1,3,4'}}
Handlebars.registerHelper("printArray", function(values){
let array = values.split(",");
console.log(array);
});
Upvotes: 0
Reputation: 21
You can define a array helper as below.
Handlebars.registerHelper('array', function() {
return Array.prototype.slice.call(arguments, 0, -1);
}
{{printArray (array 1 3 4)}}
Upvotes: 1
Reputation: 380
You need to use another helper that returns an array
Template.ArrayDemo.helpers({
arrayValues: [1, 2, 3],
printArray: function(arr) {
for (i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
}
});
now you can do
{{printArray arr=arrayValues}}
Upvotes: 2
Reputation: 31
You can almost accomplish this with the use of eval()
, using a helper like this:
Handlebars.registerHelper('printArray', function(values) {
var array = eval(values);
if (array.constructor === Array()) {
...
}
}
The above allows you to call this from the template:
{{printArray '[0, 1, 2]'}}
The one caveat to this method is that you have to pass your array as a string.
Upvotes: 3
Reputation: 8266
You can use JavaScript's arguments
array to accomplish something like this. The arguments
array gives you access to every value passed to the function when it is called.
This will allow you to use syntax like this:
{{printArray 1 3 4}}
The code looks like this:
Handlebars.registerHelper('printArray', function() {
//Last argument is the options object.
var options = arguments[arguments.length - 1];
//Skip the last argument.
for(var i = 0; i < arguments.length - 1; ++i) {
//Do your thing with each array element.
}
//Return your results...
return '';
});
Upvotes: 8
Reputation: 2209
Have you tried passing in just the bracketed value of the array?
{{printArray [1, 3, 4]}}
I know you can easily pass in objects, as arguments to the handlebars helper methods:
{{printArray {arr: [1, 3, 4]} }}
Take a look at these awesome helper methods, most of which I stole from elsewhere, a few of which I wrote or tweaked... They are my reference starting point on the topic:
https://github.com/zeroasterisk/Presenteract/blob/master/client/lib/handlebar-helpers.js
Upvotes: 1