问题
I want to use Dust.js as a client template engine. I have a data json like this:
var data = {
"Foo": [{
"somekey": "somevalue",
"otherkey": "othervalue"
}, {
"somekey": "somevalue",
"otherkey": "othervalue"
}],
"Bar": [{
"somekey": "somevalue",
"otherkey": "othervalue"
}, {
"somekey": "somevalue",
"otherkey": "othervalue"
}]
}
I do not know in advance what uppermost object keys will be - I do not know Foo
and Bar
keys, they can be any value.
So, I need to iterate through this json by keywords like key
and value
. Something like in this pseudo-code:
{% for(key, value) in data %}
{key}: {value}
{% /for %}
I know that Dust.js has {#section/}
to loop through an object. But again, you have to provide a key name:
{#extraData}
{!
Inside this section, Dust looks for
values within the extraData object
!}
Inside the section, the value of name is: {name}{~n}
{/extraData}
And I do not know extraData
name in advance.
So, does Dust.js provide a way to reference object keys/values by key
and value
keywords?
回答1:
Dust does not provide built-in iteration over objects.
However, you can add the {@iterate}
helper to do this type of iteration.
You can get it at https://www.npmjs.com/package/dustmotes-iterate
Example usage:
Data: { obj: {a:"A", b:"B", c:"C" } }
{@iterate key=obj}
{$key}:{$value} {$type}
{/iterate}
Output: a:A string b:B string c:C string
来源:https://stackoverflow.com/questions/29554132/does-dust-js-provide-a-way-to-reference-an-object-key-value-by-keywords-key-an