How to pass multiple arguments to Spacebars helper from Meteor template?
Asked Answered
S

1

8

I haven't been able to find a solid example out there.

Template.registerHelper("itemLookup", function(sku, property){
  return Items.findOne({sku: sku})[property];
});

How do I call this on the template?

I want to do something like:

{{ itemLookup sku="i3_4030U" property="title" }}

It should output

"Intel Core i3 4030U"
Serow answered 10/6, 2015 at 15:23 Comment(0)
M
24

Do not name template helpers parameters, they will be passed in the same order to your helper function :

{{ itemLookup "i3_4030U" "title" }}

EDIT :

Why then do I see examples online where they are naming the template helper parameters?

You can name parameters when including another template and you want to set its current data context to something else :

{{> childTemplate param1="A" param2="B"}}

In the child template markup you'll be able to reference {{param1}} and {{param2}}.

Another Handlebars helpers feature available in Spacebars is the "hash" optional argument value you can pass as the last argument to your helper parameters, you can use it like this :

HTML

{{helper "A" "B" namedParam1="C" namedParam2="D"}}

JS

Template.registerHelper("helper", function(param1, param2, options){
  console.log("param1 :", param1);
  console.log("param2 :", param2);
  if(options && options.hash){
    console.log("namedParam1 :", options.hash.namedParam1);
    console.log("namedParam2 :", options.hash.namedParam2);
  }
});
Maxon answered 10/6, 2015 at 15:28 Comment(7)
Guhhhhhhh...... thanks. Why then do I see examples online where they are naming the template helper parameters?Serow
Edited my answer to cover named parameters use cases in Spacebars.Maxon
Thank you! This concise summary is exactly what I was looking for!Serow
Ok, one more question (I think). In certain helpers a " " is not required. {{> afQuickField name="optionsButNoSelect" options=numSelectOptions noselect="true"}} I'm pretty sure that numSelectOptions is not in quotes because it is the name of a helper that returns an object, right?Serow
@Maxon can you mix named and unnamed parameters in the same template call?Mclane
@Serow : do not mix template inclusion syntax {{> childTemplate}} and helper syntax {{helper}} because they're not the same things. You're right in assuming that you don't need to quote parameter values that resolves to template helpers.Maxon
@Mclane : you can mix named and unnamed parameters in helper calls (see my example) but you have to name every arguments you pass to a child template when including it, note that using this feature will completely scrap the previous data context and replace it by the arguments you provide.Maxon

© 2022 - 2024 — McMap. All rights reserved.