使用 Google 闭包模板时,如何迭代 Soy 文件中的对象?
我想创建自己的模板,我可以将对象传递给该模板,并让 Soy 模板迭代该对象并提取键和值。
如果我在 JavaScript 中有 和 object 并调用 Soy 模板:
var obj = {'one':'a', 'two':b, 'three':c};
nameSpace.templateName({'paramValue': obj});
如何获取 ['one', 'two', 'third']
值?通常我会使用 jQuery 的 each()
函数,但我不确定如何在 Soy 文件中执行类似的操作而不将对象转换为数组。
我正在使用的对象具有已知的形式(没有嵌套对象,或者如果有,它们是提前知道的并进入已知的深度)。欢迎对此问题或具有嵌套对象的一般对象情况的回答。
{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}
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}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您现在可以使用
keys()
函数。You can now get them with the
keys()
function.从目前的情况来看,目前还无法做到这一点,但将来将会有。这是 Google 开发社区讨论计划的链接。
http://groups.google.com/group/closure-templates -discuss/browse_thread/thread/a65179c527580aab
目前,如果您事先不知道键,则需要将对象转换为数组才能迭代它。
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.