Handlebars帮助程序未获取变量的值

Handlebars helper not getting value of variable

本文关键字:变量 获取 帮助程序 Handlebars      更新时间:2023-09-26

我正在尝试为Handlebars/Ember应用程序创建一个自定义的"if_eq"帮助程序。使用以下语法调用帮助程序:{{#if_eq item.name'bob'}},但正在接收两个要比较的字符串值(字面意思是'item.name'和'bob]),而不是调用上下文中的值"item.name"。想知道我可能做错了什么。谢谢

下面列出了相关的代码片段,并创建了一个jsbin来说明这里的问题

帮助程序代码

Handlebars.registerHelper('if_eq', function(a, b, opts) {
    console.log( "Comparing ", a, b);
    if(a == b)
        return opts.fn(this);
    else
        return opts.inverse(this);
});

模板代码

<ul>
    {{#each item in model}}
        {{#if_eq item.name 'bob'}}
            <li>We have a bob here!</option>
        {{else}}
            <li>A non-bob</li>
        {{/if_eq}}
    {{/each}}
</ul>

Handlebars助手在绑定属性方面表现不佳。

通常,您会希望在模板中避免此类逻辑。具体来说,要么在控制器上创建一个方法,要么在对象本身上创建,这样就可以说:if item.isBob

例如。http://emberjs.jsbin.com/fudadugemu/2/edit?html,js,输出

或者你可以使用一个组件,并从中获得一些乐趣,比如:

http://emberjs.jsbin.com/buyeqenumo/2/edit

(尝试更改bob输入)