2017-02-10 80 views
2

我試圖通過使用動態屬性名稱的對象迭代它似乎並不奏效:迭代通過在handlebars.js動態屬性對象

{{#each orders["order" + name] }} 

甚至沒有這似乎是工作

{{#each orders["orderDemo"] }} 

但這:

{{#each orders.orderDemo }} 

任何解決方案來處理動態屬性名取決於其他條件或迭代?

在我的情況,我有:

{{#each types}} 
    {{#each orders[type] }} 
     <table>....</table> 
    {{/each}} 
{{/each}} 

回答

1

AFAIK 把手不提供任何內建的動態屬性的支持,但你可以註冊一個簡單的「輔助功能」是這樣的:

Handlebars.registerHelper('orders', function(parent,child,options) { 
    return parent["order"+child].map(options.fn).join`` 
}); 

,然後用它如下:

<ul> 
    {{#orders orders name}} 
     <li>{{this}}</li> 
    {{/orders}} 
</ul> 

如果你感覺遞歸,你甚至可以這樣做:

Handlebars.registerHelper('forEach', function(parent,expr,options) { 
    return parent[Handlebars.compile(expr)(this)].map(options.fn).join``; 
}); 

{{#forEach orders "order{{name}}" }} 
    <li>{{this}}</li> 
{{/forEach}} 

但是如果你有大量的數據,這將是一個性能豬。