Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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}  // undefined
    {$paramValue.keys}  // undefined
    {$paramValue.one}   // prints 'a'
    {foreach $val in $paramValue}
      // never reached
    {/foreach} 
{/template}
like image 894
Curtor Avatar asked Nov 08 '10 02:11

Curtor


2 Answers

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

{foreach $key in keys($paramValue)}
  key:   {$key}
  value: {$paramValue[$key]}
{/foreach} 
like image 98
alex Avatar answered Oct 16 '22 10:10

alex


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.

like image 1
Curtor Avatar answered Oct 16 '22 08:10

Curtor