开发者

How do I iterate over an object within a Soy file when using Google closure templates?

开发者 https://www.devze.com 2023-01-23 18:33 出处:网络
I want to create my own template which I can pass an object to, and have the Soy template iterate through the object and pull out the keys and values.

I want to create my own template which I can pass an object to, and have the Soy template iterate through the object and pull out the keys and values.

If I have and object in JavaScript and call a Soy template:

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

How do I get the ['one', 'two', 'three'] values? Usually I would use jQuery's each() function, but I am not sure how to do something similar in Soy files without converting the object to an array.

The objects I am using have known form (there are no nested objects, or if there are, they are known ahead of time and go to known depth). Answers for this or the general object case with nested objects are welcome.

{namespace nameSpace}

/**
 * Prints keys and values of the object
 * @param paramValue object with keys and values
 */
{template .templateName}
    {$paramValue[0]}    // undefined
    {$paramValue.Keys}  // undefin开发者_运维知识库ed
    {$paramValue.keys}  // undefined
    {$paramValue.one}   // prints 'a'
    {foreach $val in $paramValue}
      // never reached
    {/foreach} 
{/template}


You can now get them with the keys() function.

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


By the looks of things, this is not available at this time, but it will be in the future. Here is a link to Google Development community discussing plans for it.

http://groups.google.com/group/closure-templates-discuss/browse_thread/thread/a65179c527580aab

Currently, you need to transform your object into an array in order to iterate over it, if you do not know the keys ahead of time.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号