2015-07-22 95 views
4

在Python,反覆給我一個命名的變量:如何在ractive.js中獲得一個命名的循環變量?

for cage in cages: 
    for animal in cage.animals: 
     print("The current cage is",cage) 
     print("the current animal is",animal) 

在Ractive模板,我似乎沒有能夠做到這一點。

{{#cages}} 
    {{#animals}} 
     The current animal is {{.}} or {{this}}, 
     but I don't know how to refer to the current cage, 
     i.e. the outer loop variable 

     I would like to be able to say {{cage}} has an {{animal}} 
    {{/animals}} 
{{/cages}} 

有沒有我不知道的語法?

回答

4

沒有明確的語法,據我所知,但你可能(MIS)使用aliases爲:創建一個新的上下文,它重命名.cage,例如。它看起來像這樣:

{{#cages}} {{# {cage: .} }} 
    {{ cage.name }} 
{{/}}{{/cages}} 

一個完整的版本是on JSFiddle

使用,因爲在Ractive,你通常在當前上下文對象的性能沒有命名上下文對象本身的工作。這也適用於嵌套的情況。因此,這沒有語法。

其中別名確實有意義:name-shadowing。如果您需要在內部循環中訪問與動物財產同名的籠子屬性,則別名將發揮作用。兩者都是demonstrated in another fiddle

5

我想知道是否應該添加{{#each cage in cages}}{{#each cages as cage}}語法來處理這些情況。取而代之的是,mknecht的答案完全有效,而且我經常用我自己的東西;另一種方法是創建索引的參考,像這樣:

{{#each cages :c}} 
    {{#each animals}} 
    The current animal is {{this}}, the current cage 
    is {{cages[c]}} 
    {{/each}} 
{{/each}} 

用這種方法不同的是,雙向綁定仍然會工作(儘管它聽起來不像是在這種情況下一個問題。)

+0

我非常希望看到'{{#each cage in cage}}或'{{#each cages as cage}}',這會使編寫嵌套循環變得更容易。 – trvrm