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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4120914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:25:26  来源:igfitidea点击:

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

javascriptgoogle-closure

提问by Curtor

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? 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.

我如何获得这些['one', 'two', 'three']值?通常我会使用 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}

回答by alex

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

您现在可以使用该keys()功能获取它们。

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

回答by Curtor

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 开发社区讨论其计划的链接。

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.

目前,如果您事先不知道键,您需要将对象转换为数组以对其进行迭代。