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

Curtor picture Curtor · Nov 8, 2010 · Viewed 10.7k times · Source

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}

Answer

alex picture alex · Jun 27, 2013

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

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