在哈巴狗中迭代错误

时间:2017-02-23 09:25:42

标签: javascript node.js express pug

编辑已添加GIST

我在使用pug迭代对象数组时遇到了困难:

app.render

response.render('layout', {
    title: 'Visual Display',
    slides: shuffledData
});

layout.pug

html
    head
        title= title
    body
        each slide in slides
            p= slide.type

错误消息

TypeError: /home/chris/Projects/visualdisplay/src/views/layout.pug:6
   4|     body
   5|         each slide in slides
 > 6|             p= slide.type

Cannot read property 'type' of undefined
   at eval (eval at wrap (/home/chris/Projects/visualdisplay/node_modules/pug-runtime/wrap.js:6:10), <anonymous>:23:62)

如果我将reponse.render更改为response.send(以查看正在发送的数据),我会得到: 我在示例中修改了一些数据值

[{
    "type": "achievement",
    "studentCode": 110399,
    "studentFirstName": "xx",
    "studentMiddleName": "xx",
    "studentLastName": "xx",
    "studentHouse": "Eagles",
    "achievementType": "Academic",
    "achievementDescription": "well done in house point competition in maths",
    "achievementDate": "2017-02-23T00:00:00.000Z",
    "staffPreferredFirstName": "",
    "staffFirstName": "xx",
    "staffLastName": "xx"
}, {
    "type": "achievement",
    "studentCode": 102797,
    "studentFirstName": "xx",
    "studentMiddleName": "xx",
    "studentLastName": "xx",
    "studentHouse": "Oryx",
    "achievementType": "Academic",
    "achievementDescription": "Well done in revision Kahoot on exponents and natural logs",
    "achievementDate": "2017-02-23T00:00:00.000Z",
    "staffPreferredFirstName": "",
    "staffFirstName": "xx",
    "staffLastName": "xx"
}, {
    "type": "tweet",
    "user": {
        "name": "xx",
        "screenName": "xx",
        "description": "",
        "profileImage": "xx"
    },
    "tweet": {
        "date": "Mon Feb 20 16:21:04 +0000 2017",
        "text": "xx",
        "mediaURL": "xx"
    }
}]

如果我将哈巴狗代码更改为

html
    head
        title= title
    body
        each slide in slides
            p testline

它会在幻灯片中发送的数据表中重复正确的次数。

此外,如果我执行类似p = slides [0] .type的操作,它将正确找到值。

我正在使用最新的哈巴狗,并从npm表达。

发生了什么事?

1 个答案:

答案 0 :(得分:0)

使用此功能,您可以使用-设置变量,然后使用#{varName}打印值,如果要渲染值(例如,您有一些html标记),则可以使用!{varName}

 html
 head
        title= title
    body
        each slide in slides
          -slideType = slide.type
           #{slideType}

作为一个简单的工作示例,您可以使用externals jade(pug)到html转换器:

-slides = [{"id":"1", "type":"html", "value":"<strong>strong text</strong>"}, {"id":"2", "type":"plain-text", "value":"plain text"}]

    each slide in slides
       div !{slide.value}
       div #{slide.value}