Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor - What is Spacebars.kw {hash: Object}

I'm attempting to write a Meteor package which can be placed inside templates. So I first attempted to register a helper.

Template.registerHelper('testHelper', function(a, b) {
        console.log(a);
        console.log(b);
})

I've added the package inside /packages, and in my client template, when I added {{testHelper "hello" "meow"}}, the console logged hello and meow, which is what I expected.

When I added {{testHelper "hello"}}, I expected the console to log hello and null, since nothing was passed as the second parameter. But instead it returned hello and an object - Spacebars.kw {hash: Object}

What is this Spacebars.kw {hash: Object}? What can I do if I want it to return null instead?

like image 592
dayuloli Avatar asked Jan 03 '15 14:01

dayuloli


1 Answers

Spacebars.kw contains a hash object that has a hash of input parameters.

Meteor has two methods to match up methods, one is direct matching which is where the parameters are directly input, e.g {{testHelper "variable1" "variable2" "variable3"}}, would match up as function(a,b,c) as variables 1-3 matching up to a,b and c respectively.

The second method of input is using a hash:

{{testHelper a="variable1" b="variable2" c="variable3"}}

This would give a single parameter to function(a) where a is a Spacebars.kw object.

The Spacebars.kw object would have a subobject called hash with a structure that matches:

{ "a" : "variable1",
  "b" : "variable2",
  "c" : "variable3" }

Meteor will attempt to match up the first param directly, but the subsequent parameters will be matched up as hashes incase the second input is empty such as in the case where you use {{testHelper 'hello'}} where b would be null, so it's given as the hash instead.

Its generically given as this, so if you get b as a Spacebars.kw object, you can assume there was no second input. The alternative is you could use the hash style declarations and then directly check if the hash value is null:

{{testHelper text="Hello"}}
{{testHelper text="Hello" othertext="Hellooo"}}

and the helper:

Template.registerHelper('testHelper', function(kw) {
    console.log(kw.hash.text);
    console.log(kw.hash.othertext);
});
like image 50
Tarang Avatar answered Sep 30 '22 18:09

Tarang