2

In Meteor, we can pass values to a helper like so:

{{testHelper abc="123" xyz="987"}}

and the helper:

Template.registerHelper('testHelper', function(opt) {
    console.log(opt.hash.abc);
    console.log(opt.hash.xyz);
});


Is there a way to do just:
{{testHelper "123" "987"}}

and get the values back as an index instead? Like so:

Template.registerHelper('testHelper', function(opt) {
    console.log(opt.hash[0]);
    console.log(opt.hash[1]);
});

I know you can define a function which takes two arguments, like in this answer, and it'd work. But I'd ideally want the function to take any number of arguments.

If I console.log(opt); here, I'd get 123, whereas I want opt.hash[0] (or, even better, opt[0]) to be 123, and opt.hash[1] to be 987.

The reason I want this is

  1. "123" looks cleaner than abc="123" when the key value doesn't matter,
  2. but still allow the helper to accept any number of parameters.

I have tried passing an array as a parameter {{testHelper ["123", "987"]}}, but that produced a syntax error.

Community
  • 1
  • 1
dayuloli
  • 16,205
  • 16
  • 71
  • 126

2 Answers2

3

This is a bit of an older question, but I just tested and something like this works:

// JS
Template.registerHelper('concat', function () {
    return Array.prototype.slice.call(arguments, 0, -1).join('');
});

// Template
{{ concat "a" "b" "c" }}

Basically, the normal JavaScript arguments value is still available in a helper.

The last argument is always the Spacebars object (the one with the hash), but if you slice that off like I did (Array.prototype.slice.call(arguments, 0, -1)), you basically get all of the other arguments in an array, which you can then use as you like.

samanime
  • 25,408
  • 15
  • 90
  • 139
1

So this might not be a perfect solution but you can pass in an array if a helper for it already exists, so assuming you have a way to inject the values into the helper array, for instance with Session, you can access it in your original method.

Session.set('tempArray', ['abc', 'xyz']);

Template.registerHelper('tempArray', function() {
  return Session.get('tempArray');
});

Template.registerHelper('readArray', function(arr) {
  console.log(arr[0]);
});

<!-- template -->
{{readArray tempArray}}

//outputs: 'abc'
azium
  • 20,056
  • 7
  • 57
  • 79