使用车把助手arrarify将对象的对象转换为对象数组。
handlebarsHelper.js
Handlebars.registerHelper('arrayify',function(obj){
result = [];
for (var key in obj) result.push({name:key,value:obj[key]});
return result;
});client/views/main.html
<template name="orderList">
{{#each arrayify orderList}}
{{value.amount}} {{ value.name }}
{{/each}}
</template>client/views/main.js
Template.orderList.orderList = function() {
// Retrieved from Collection
orderList = {
12345: {name: "apples_mackintosh", amount: 10},
12346: {name: "oranges_sunkiss", amount:5}
};
return orderList;
};问题:如何将模板值oranges_sunkiss呈现为oranges,apples_mackintosh' as 'apples?我尝试使用.split('_')[0],但Meteor抛出了一个错误
client/views/main.html
<template name="orderList">
{{#each arrayify orderList}}
{{value.amount}} {{ value.name.split('_')[0] }}
{{/each}}
</template>误差
While building the application:
client/views/main.html:63: Parse error:
...unt}} {{ value.name.split('_')[0] }} @ {
-----------------------^
Expecting 'ID', got 'INVALID'发布于 2013-11-20 15:38:27
我相信正在发生的事情是,您正在尝试在工具栏模板中使用JS代码。这是一个常见的问题/烦恼,但这样做有一个很好的理由:实际的模板应该没有逻辑和代码。模板应该是“哑”的,并且只用于显示目的。对于特定示例,将字符串拆分移动到在main.js中创建main.js时
Template.orderList.orderList = function() {
// Retrieved from Collection
orderList = {
12345: {name: "apples_mackintosh".split('_')[0], amount: 10},
12346: {name: "oranges_sunkiss".split('_')[0], amount:5}
};
return orderList;
};发布于 2013-11-20 15:48:34
首先将其存储在某个变量中,然后通过javascript将其拆分,或者创建一些将被调用的助手函数,然后返回拆分的值。
https://stackoverflow.com/questions/20099807
复制相似问题