首页 > 解决方案 > 如何在 Handlebars 中显示从 express js 传输的数据?

问题描述

我用express js中的render函数发送数据,数据的形式

 [
  {
    id_customers: 1,
    name_company: 'dsfsd',
    nip: 23423,
    adres: 'dsfsd',
    phone_number: '23423',
    createdAt: 2019-12-31T23:00:00.000Z,
    updatedAt: 2019-12-31T23:00:00.000Z
  },
  {
    id_customers: 2,
    name_company: 'nokia',
    nip: 23232323,
    adres: 'dfsd',
    phone_number: '23123123',
    createdAt: 2019-12-31T23:00:00.000Z,
    updatedAt: 2019-12-31T23:00:00.000Z
  }
]

我如何在车把上显示这些?

标签: expresshandlebars.js

解决方案


这是一个使用handlebarswith expressand的示例express-handlebarshttps ://codesandbox.io/s/display-datas-handlebars-pftcs

index.js

    var express = require("express");
    var exphbs = require("express-handlebars");
    
    var app = express();
    
    app.engine("handlebars", exphbs());
    app.set("view engine", "handlebars");
    
    app.get("/", function (req, res) {
      res.render("home", {
        customers: [
          {
            id_customers: 1,
            name_company: "dsfsd",
            nip: 23423,
            adres: "dsfsd",
            phone_number: "23423"
          },
          {
            id_customers: 2,
            name_company: "nokia",
            nip: 23232323,
            adres: "dfsd",
            phone_number: "23123123"
          }
        ]
      });
    });
    
    app.listen(8080);

视图/布局/main.handlebars

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Example App</title>
</head>

<body>

  {{{body}}}

</body>

</html>

视图/home.handlebars

<ul class="people_list">
  {{#each customers}}
  <li>{{this.name_company}} - {{this.adres}}</li>
  {{/each}}
</ul>

推荐阅读