在express中使用pug(jade)创建表并添加数据

时间:2019-07-17 13:20:51

标签: express pug

我正在用玉石制作一个桌子。我无法在表中输入值。我正在处理一条产品路线。

index.js

var express = require('express'),
    path = require('path'),
    home = require('./routes/home.js');

var app = express();

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

app.use('/home', home);

app.listen(3000);
console.log('Access through http://localhost:3000/');

home.js

var express = require('express');
var router = express.Router();

router.get('/home', function(req, res) {
  res.render('home/index', { id:'1',name:'hp', quantity:'3'},{ id:'2',name:'dell', quantity:'2'},{ id:'3',name:'sony', quantity:'5'});

});
module.exports = router;

index.jade

doctype
html
  head
    title=title
  body
    h3 Comments
    table
      tr
        th Id
        th Name
        th Quantity
      each item in item
         tr
            td #{item.id}
            td #{item.name}
            td #{item.quantity}

1 个答案:

答案 0 :(得分:0)

您应该在单个对象中将局部变量传递给Pug。将项目对象编写为数组将有助于对其进行迭代。在您的home.js中尝试以下操作:

res.render('home/index', {
    items: [
        { id:'1', name:'hp',   quantity:'3' },
        { id:'2', name:'dell', quantity:'2' },
        { id:'3', name:'sony', quantity:'5' }
    ]
});

然后在您的Pug中,对each循环中的两个项目(“ item”与“ items”)使用不同的变量名很重要:

each item in items
    tr
        td #{item.id}
        td #{item.name}
        td #{item.quantity}