【问题标题】:Iterating over an array in Pug在 Pug 中迭代一个数组
【发布时间】:2017-10-11 14:17:39
【问题描述】:

我正在从外部 API 以 JSON 格式检索数据并将该数据发送到我的视图。我遇到的问题是,对象中的一个属性是对象数组。按照 Pug 文档 (Pug Iteration),我可以像这样成功地遍历数组:

block content
  .row
    each item in data.array
      .col-md-3
        .well
          img(src=`${item.media.m}`)
          h5 #{item.title}
          p by #{item.author}

但是,Array 存储 20 个值,理想情况下,我想一次迭代四个值,以便获得以下输出:

<div class="row">
  <div class="col-md-3">
    <div class="well">
      <img src="https://localhost/frank_the_pug.jpg">
      <h5>Frank the Pug</h5>
      <p>by MIB</p>
    </div>
  </div>
</div>
<div class="row">
  <div class="col-md-3">
    <div class="well">
      <img src="https://localhost/frank_the_pug2.jpg">
      <h5>Frank the Pug 2</h5>
      <p>by MIB</p>
    </div>
  </div>
</div>

编辑:

JSON 结构

{
  "string": "string",
  "string": "string",
  "array": [
    {
      "string": "string",
      "media": {
        "m": "string"
      }
    },
    {
      "string": "string",
      "media": {
        "m": "string"
      }
    }
  ]
}  

【问题讨论】:

  • 据我了解你的问题,你可能应该再循环一次,或者改变你格式化数据的方式,你能不能显示你的数据结构?
  • 嗨 Fabian,你说得对,在输出 .row div 之前,我需要再次循环,所以我可以输出一个 .row div 和四个 .col-md-3 divs。你会怎么做?

标签: javascript node.js express pug


【解决方案1】:

您可以先将项目按 4 分组,然后使用两个嵌套循环遍历组和组中的项目

- const groupBy4 = arr => arr.reduce((acc, item) => {
-    let last = acc[acc.length - 1]
-    if(last.length === 4) {
-      acc.push(last = []);
-    }
-    last.push(item)
-    return acc;
- }, [[]])

each group in groupBy4(items)
  .row
    each item in group
      .col-md-3
        .well
          img(src=item.media.m)
          h5 #{item.title}
          p by #{item.author}

【讨论】:

  • 谢谢,尤里。这看起来不错,将 groupBy4() 函数放在单独的文件中,然后将其包含到我们的 pug 模板中,最佳实践是什么?
  • 你可以通过从单独的文件中要求它来传递本地函数。
猜你喜欢
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 2011-07-07
  • 2015-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-02
相关资源
最近更新 更多