2010-11-08 16 views
12

我想創建我自己的模板,我可以傳遞一個對象,並讓大豆模板遍歷該對象並提取鍵和值。如何在使用Google閉包模板時迭代Soy文件中的對象?

如果我有和JavaScript對象並調用模板大豆:

var obj = {'one':'a', 'two':b, 'three':c}; 
nameSpace.templateName({'paramValue': obj}); 

如何獲得['one', 'two', 'three']值?通常我會使用jQuery的each()函數,但我不確定如何在Soy文件中做類似的事情,而無需將對象轉換爲數組。

我使用的對象有已知的形式(沒有嵌套的對象,或者如果有的話,它們會提前知道並轉到已知深度)。對於這個或嵌套對象的一般對象情況的答案是受歡迎的。

{namespace nameSpace} 

/** 
* Prints keys and values of the object 
* @param paramValue object with keys and values 
*/ 
{template .templateName} 
    {$paramValue[0]} // undefined 
    {$paramValue.Keys} // undefined 
    {$paramValue.keys} // undefined 
    {$paramValue.one} // prints 'a' 
    {foreach $val in $paramValue} 
     // never reached 
    {/foreach} 
{/template} 

回答

20

您現在可以通過keys()函數獲取它們。

{foreach $key in keys($paramValue)} 
    key: {$key} 
    value: {$paramValue[$key]} 
{/foreach} 
+1

這絕對是今天的正確答案。請參閱以下文檔:https://developers.google.com/closure/templates/docs/functions_and_directives – 2014-11-24 22:45:25

+1

keys()不尊重原始鍵的順序(在文檔中註明)。在語義上這不是問題,但在實踐中,您可能需要注意這一點。 – 2015-06-26 07:58:35

相關問題