【问题标题】:Iterate over object array and return to jade template遍历对象数组并返回翡翠模板
【发布时间】:2016-04-01 19:58:48
【问题描述】:

我有一个需要传递的数组来表达、渲染,然后在 Jade 端迭代以显示所有结果,但是下面的函数不起作用。它只显示一条数据,来自数组的五次。预期的行为是它将遍历数组并显示模板中的每个对象之一。

jade 和 express 的语法是否正确?文档很简单。

截图

快递

router.get('/', function(req, res, next){
  weekendPlans(function(err, theWeekend) {
      if (err) throw err
      console.log(theWeekend);
      res.render('index', {theWeekend : theWeekend});
});

翡翠

  h2 On This Weekend
  .scroll
    each result, i in theWeekend
      div.title
        #[a(target="_blank" href="#{theWeekend.url}") #{theWeekend.title}]
        p WHEN: #{theWeekend.selectedDate}

数据

{ _id: 56fe9fe71f84acc2564b9fe8,
  url: 'http://www.timeoutshanghai.com/features/Blog-Food__Drink/35271/Baristas-showcase-latte-art-in-Shanghai.html',
  title: 'TIMEOUT',
  selectedDate: Sat Apr 02 2016 01:00:00 GMT+0100 (BST),
  __v: 0 }

【问题讨论】:

    标签: express pug


    【解决方案1】:

    什么数组?我能看到的只是一个物体。您正在遍历一个对象。并且对于对象中的每个键,您都可以让翡翠打印出一个带有锚点和段落的 div。由于您的对象包含五个键,因此您将获得五个 div。

    这就是为什么当你写result.key 时它什么也没给你,因为那不存在。在那种情况下,result[1] 会给你网址。当你写 theWeekend.key 时,它每次都会给你相同的文本。

    如果您只有一个对象,则不需要循环。你应该写:

    .scroll
          div.title
            #[a(target="_blank" href="#{theWeekend.url}") #{theWeekend.title}]
            p WHEN: #{theWeekend.selectedDate}
    

    【讨论】:

    • 我以后会有更多的对象,如果不清楚,对不起,
    • 好吧,那么。将来当“theWeekend”实际上是一个对象数组时,您应该在您的翡翠循环中使用 result.url、result.title 等。祝你好运!
    【解决方案2】:

    在您的 Jade 文件中,您正在对数据对象进行迭代,该对象针对对象中的每个键值对循环一次。如果您只需要数据对象的一个​​条目,请尝试以下操作:

    div.title
      #[a(target="_blank" href="#{theWeekend.url}") #{theWeekend.title}]
      p WHEN: #{theWeekend.selectedDate}
    

    它应该可以工作。

    【讨论】:

    • 我之前尝试过,它仍然给了我五个结果,除了没有数据。很混乱。还有其他想法吗?
    • console.log(theWeekend) 的输出是什么; ?
    • 输出的是原题中的数据
    • 你希望在页面上显示什么?
    • 我已经编辑了我的答案。但请允许我再问一个问题:为什么您的问题涉及数组并遍历所有条目?
    猜你喜欢
    • 1970-01-01
    • 2016-03-09
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 2013-05-19
    • 1970-01-01
    相关资源
    最近更新 更多