简体   繁体   English

使用Google闭包模板时,如何在Soy文件中迭代对象?

[英]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. 我想创建自己的模板,我可以传递一个对象,并让Soy模板迭代对象并拉出键和值。

If I have and object in JavaScript and call a Soy template: 如果我在JavaScript中有对象并调用Soy模板:

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

How do I get the ['one', 'two', 'three'] values? 如何获得['one', 'two', 'three']值? 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. 通常我会使用jQuery的each()函数,但我不知道如何在没有将对象转换为数组的情况下在Soy文件中做类似的事情。

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}

You can now get them with the keys() function. 您现在可以使用keys()函数获取它们。

{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. 以下是Google Development社区讨论计划的链接。

http://groups.google.com/group/closure-templates-discuss/browse_thread/thread/a65179c527580aab 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. 目前,如果您不提前知道密钥,则需要将对象转换为数组以便迭代它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM