【问题标题】:Displaying key-value-pairs out of an array by using a template使用模板显示数组中的键值对
【发布时间】:2014-09-13 02:12:21
【问题描述】:

我想使用#each 模板指令显示存储在数组中的键值对(从 Session-JSON 变量派生)。如何访问(如果可能)数组中对象的字段。

对不起,如果这是一个已经回答的问题,但我在这里没有找到合适的答案。

这里是一些示例代码(模板助手的一部分):

attributes: function () {
        var attributes = [];
        attributes = [{key: test1, value: 1}, {key: test3, value: 2}, {key: test3, value: 3}];
        return attributes;
    },

在模板中,我使用了“this”或“this.key”。两者都没有按预期工作。

感谢任何提示!

【问题讨论】:

    标签: meteor


    【解决方案1】:

    您是否定义了变量test1test3?看起来你把 test1test3 不带 ",所以这意味着 js 正在尝试查找具有此类名称的变量。这就是为什么你看不到 this.key 工作的原因。

     var attributes = [];
     attributes = [{key: "test1", value: 1}, {key: "test2", value: 2}, {key: "test3", value: 3}];
     return attributes;
    

    在模板中:

    {{#each attributes}}
       {{this.key}} : {{this.value}}<br>
    {{/each}}
    

    输出:

    test1 : 1<br>
    test2 : 2<br>
    test3 : 3<br>
    

    Check here

    【讨论】:

    • 太好了,有时你会忘记最简单的事情......!非常感谢!
    猜你喜欢
    • 2020-09-29
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多