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"

1 Answer 1

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);
  }
});
7
  • Guhhhhhhh...... thanks. Why then do I see examples online where they are naming the template helper parameters? Jun 10, 2015 at 15:35
  • Edited my answer to cover named parameters use cases in Spacebars.
    – saimeunt
    Jun 10, 2015 at 16:01
  • 1
    Thank you! This concise summary is exactly what I was looking for! Jun 10, 2015 at 16:04
  • 1
    @fuzzybabybunny : 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.
    – saimeunt
    Jun 10, 2015 at 16:40
  • 1
    @Aaron : 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.
    – saimeunt
    Jun 10, 2015 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.