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

1

6

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?

Atomizer answered 3/1, 2015 at 14:28 Comment(0)
M
14

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);
});
Musetta answered 3/1, 2015 at 15:34 Comment(2)
Thank you Akshat once again, you're a star! I have followed the hash style declarations and it works great. I do have a follow up question which I will post as a new question. By the way, is this Spacebars.kw documented? I can't find it in the docs, maybe we can add this to the docs?Atomizer
what does kw stand for ?Bradshaw

© 2022 - 2024 — McMap. All rights reserved.