用小胡子遍历 JSON 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17283776/
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-09-03 19:53:14  来源:igfitidea点击:

iterate through JSON array with mustache

jsonmustache

提问by Liang

I am new to Mustache, please bear with me :)

我是 Mustache 的新手,请耐心等待:)

I have an array in my JSON

我的 JSON 中有一个数组

"prop":{"brands":["nike","adidas","puma"]}

if I have the template like this

如果我有这样的模板

{{#prop}}
 <b>{{brands}}</b>
{{prop}}

and I want to get something like:

我想得到类似的东西:

<b>nike</b>
<b>adidas</b>
<b>puma</b>

I understand the elements in the array are not hash key-value pairs, however I am wondering if there is anyway in mustache that I can iterate through the elements.

我知道数组中的元素不是哈希键值对,但是我想知道是否有胡子可以遍历元素。

Thanks!

谢谢!

采纳答案by Paul

mustache is logicless, so writing your own iteration/loop in it is impossible. It is easy to convert your JSON though. For example:

mustache 是没有逻辑的,因此在其中编写自己的迭代/循环是不可能的。不过,转换 JSON 很容易。例如:

var json = '{"prop":{"brands":["nike","adidas","puma"]}}';
var obj = JSON.parse(json);
var data = {brands: obj.prop['brands'].map(function(x){ return {name: x}; })};

Gives you a datavariable which will work with the template:

为您提供一个data可与模板一起使用的变量:

{{#brands}}
  <b>{{name}}</b>
{{/brands}}

回答by peshkira

Here is a working fiddle: http://jsfiddle.net/Qa4UX/

这是一个工作小提琴:http: //jsfiddle.net/Qa4UX/

Basically, you need to iterate over the brands array. Since your array is raw and does not have objects inside you have to reference each string like so:

基本上,您需要遍历品牌数组。由于您的数组是原始数组并且内部没有对象,因此您必须像这样引用每个字符串:

{{#props}}
  <ul>
  {{#brands}}
    <li>
    {{#.}}
        <b>{{.}}</b>
    {{/.}}
    </li>
  {{/brands}}
  </ul>
{{/props}}

You can also find many more examples over here: https://github.com/janl/mustache.js#mustachejs---logic-less-mustache-templates-with-javascript

您还可以在这里找到更多示例:https: //github.com/janl/mustache.js#mustachejs---logic-less-mustache-templates-with-javascript

回答by Ariel

This works

这有效

{{#json.props.brands}}
<h1>{{.}}</h1>
{{/json.props.brands}}

{{.}}When looping over an array of strings, a .can be used to refer to the current item in the list.

{{.}}循环遍历字符串数组时,.可以使用 a 来引用列表中的当前项。