【问题标题】:Meteor - What is Spacebars.kw {hash: Object}Meteor - 什么是 Spacebars.kw {hash: Object}
【发布时间】:2015-03-01 14:17:32
【问题描述】:

我正在尝试编写一个可以放置在模板中的 Meteor 包。所以我首先尝试注册一个助手。

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

我已经在/packages 中添加了包,在我的客户端模板中,当我添加{{testHelper "hello" "meow"}} 时,控制台记录了hellomeow,这是我所期望的。

当我添加{{testHelper "hello"}} 时,我希望控制台记录hellonull,因为没有任何内容作为第二个参数传递。但相反,它返回了 hello 和一个对象 - Spacebars.kw {hash: Object}

这是什么Spacebars.kw {hash: Object}?如果我希望它返回 null,我该怎么办?

【问题讨论】:

    标签: meteor spacebars


    【解决方案1】:

    Spacebars.kw 包含一个 hash 对象,该对象具有输入参数的哈希值。

    Meteor有两种匹配方法,一种是直接匹配,即直接输入参数,例如{{testHelper "variable1" "variable2" "variable3"}},将匹配为function(a,b,c)作为变量1-3匹配a,b和c分别。

    第二种输入方法是使用散列

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

    这将为function(a) 提供一个参数,其中a 是Spacebars.kw 对象。

    Spacebars.kw 对象将有一个名为 hash 的子对象,其结构匹配:

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

    Meteor 将尝试直接匹配第一个参数,但后续参数将匹配为哈希值,以防第二个输入为空,例如在您使用 {{testHelper 'hello'}} 的情况下,b 将为空,所以它是作为散列给出的。

    它通常是这样给出的,所以如果你得到 b 作为Spacebars.kw 对象,你可以假设没有第二个输入。另一种方法是您可以使用哈希样式声明,然后直接检查哈希值是否为null

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

    和助手:

    Template.registerHelper('testHelper', function(kw) {
        console.log(kw.hash.text);
        console.log(kw.hash.othertext);
    });
    

    【讨论】:

    • 再次感谢 Akshat,你是明星!我遵循了哈希样式声明,效果很好。我确实有一个后续问题,我将作为一个新问题发布。顺便说一句,这个Spacebars.kw 有记录吗?我在文档中找不到它,也许我们可以将它添加到文档中?
    • kw 代表什么?
    猜你喜欢
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2014-10-24
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 2011-07-14
    相关资源
    最近更新 更多