Does Dust.js provide a way to reference an object key/value by keywords “key” and “value”?

前提是你 提交于 2019-12-25 02:57:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!