如何使用 Mustache 使用任意键渲染 json?

发布于 2024-10-31 07:39:46 字数 473 浏览 5 评论 0原文

我有一个如下所示的 JSON 对象:

{
    "XXX":{"name":"First"},
    "YYY":{"name":"Second"},
    ....
}

我需要将其渲染为如下所示:

<div>
    <h1>XXX</h1>
    <p>First</p>
</div>
<div>
    <h1>YYY</h1>
    <p>Second</p>
</div>
....

我将如何使用 小胡子?我面临的问题是我不知道如何引用这些项目,因为键名称是任意的。

I have a JSON object that looks like the following:

{
    "XXX":{"name":"First"},
    "YYY":{"name":"Second"},
    ....
}

I need to render it to look like:

<div>
    <h1>XXX</h1>
    <p>First</p>
</div>
<div>
    <h1>YYY</h1>
    <p>Second</p>
</div>
....

How will I accomplish this using Mustache? The problem I am facing is that I don't know how to reference the items because the key names are arbitrary.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

拿命拼未来 2024-11-07 07:39:46

使用您最喜欢的 JSON 解析器将 JSON 转换为哈希,这将给您如下所示的结果:

json = {
    "XXX" => {"name" => "First"},
    "YYY" => {"name" => "Second"},
    "ZZZ" => {"name" => "Third"}
}

然后只需将其重新排列为具有已知键的小哈希列表:

for_mustache = json.keys.inject([ ]) do |a, k|
    a.push({ :k => k, :v => json[k]['name']})
    a
end

上面可能有更聪明的方法来做到这一点。现在,您将在 for_mustache 中得到像这样简单且常规的内容:

[
    { :k => "XXX", :v => "First"  },
    { :k => "YYY", :v => "Second" },
    { :k => "ZZZ", :v => "Third"  }
]

然后您可以像 Mustache 中的任何其他哈希数组一样处理该数据结构:

{{#for_mustache}}
    <div>
        <h1>{{k}}</h1>
        <p>{{v}}</p>
    </div>
{{/for_mustache}}

Convert the JSON to a hash using your favorite JSON parser, that will give you something that looks like this:

json = {
    "XXX" => {"name" => "First"},
    "YYY" => {"name" => "Second"},
    "ZZZ" => {"name" => "Third"}
}

Then simply rearrange it into a list of little hashes with known keys:

for_mustache = json.keys.inject([ ]) do |a, k|
    a.push({ :k => k, :v => json[k]['name']})
    a
end

There are probably cleverer ways to do that above. Now you'll have something simple and regular like this in for_mustache:

[
    { :k => "XXX", :v => "First"  },
    { :k => "YYY", :v => "Second" },
    { :k => "ZZZ", :v => "Third"  }
]

Then you can handle that data structure just like any other array of hashes in Mustache:

{{#for_mustache}}
    <div>
        <h1>{{k}}</h1>
        <p>{{v}}</p>
    </div>
{{/for_mustache}}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文