node.js - 使用 Handlebars 访问数组中所有对象的特定元素时出现问题

标签 node.js express express-handlebars

我对 Handlebars 比较陌生,所以这可能是我缺少的一些简单的东西,但我似乎无法输出数组中每个对象的特定元素。我已经搜索了多个帖子并阅读了 Handlebars 文档,但到目前为止还没有找到解决方案。基本上,我试图输出一系列时间段的可用性及其分配给一个项目的状态。这是我的代码...

数据

Pitch: {
"name": "test",
"price": 11,
"city": "testCity",
"availability": [
    {
        "status": "reserved",
        "dt": "2018-11-16T20:00:00Z"
    },
    {
        "status": "available",
        "dt": "2018-11-16T19:00:00Z"
    }
]
}

index.js

router.get('/availability/:id', function(req, res, next) {
Pitch.findById(req.params.id, function (err, docs){
    var indPitch = [];
    indPitch.push(docs);

    res.render('pitch/availability', { title: 'Availability', indPitch: indPitch });

});

可用性.hbs

{{#each indPitch}}
        <h3><a href="/availability/{{ id }}">{{ name }}</a></h3>
        <p class = "description">{{ city }}</p>
        {{#each availability}}
          {{status}}
          {{dt}}
        {{/each}}
        <p class = "description">Price per hour : €{{ price }}</p>
        <a href="/reserve/{{id}}" class="btn btn-primary pull-right" role="button">Select</a>
{{/each}}

使用上面的 Handlebars 代码,仅将城市和价格输出到屏幕上。如果我将 {{#eachavailability}} 更改为 {{#each this}},然后以 {{availability.[0].status}} 或 {{availability.[1].dt}} 等形式访问该对象。然后我可以将该项目输出到屏幕上。

但是,我需要做的是循环遍历该项目的“可用性”并显示所有日期/时间及其状态。有什么想法我做错了吗?如果您需要更多信息,请告诉我。

最佳答案

只需在每个元素之前使用它就可以了

 {{#each indPitch}}
    <h3><a href="/availability/{{ id }}">{{this.name }}</a></h3>
    <p class = "description">{{ this.city }}</p>
    {{#each availability}}
      {{this.status}}
      {{this.dt}}
    {{/each}}
    <p class = "description">Price per hour : €{{ this.price }}</p>
    <a href="/reserve/{{this.id}}" class="btn btn-primary pull-right" role="button">Select</a>

{{/每个}}

关于node.js - 使用 Handlebars 访问数组中所有对象的特定元素时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53336961/

相关文章:

javascript - 使用 Node.js 和 Express.js 在 MySQL 中删除给定值数组的多行

node.js - 在 ':bower' 任务上运行 JHipster gradlew 失败

node.js - 将 SAML 与 JWT 用于 Node API

javascript - 如何在react front中显示 Node 数组

node.js - 对 HEAD 请求使用 express sendFile

express - node.js connect-flash 消息不显示

javascript - 如何通过 Express 使用 Handlebars?

html - 使用nodemailer发送模板电子邮件,样式损坏

javascript - 从#each 输入列表中获取特定用户

java - RabbitMQ:在 Node.js 中发布,在 Java 中订阅