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

本小妞迷上赌 提交于 2019-12-01 02:49:41

问题


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?


回答1:


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);
});


来源:https://stackoverflow.com/questions/27755891/meteor-what-is-spacebars-kw-hash-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!