哈巴狗迭代:无法读取未定义的属性“长度”

时间:2018-10-02 10:09:46

标签: express pug

我在js文件中包含以下数据:

let data =[
  {id:1,type:"action"},
  {id:2,type:"comedy"}
];

并尝试使用哈巴狗模板打印

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='stylesheets/style.css')
  body

        table
          tr
            th Id
            th Type
          each post in data
            tr
              td #{post.id}
              td #{post.type}
  block content

我在每个帖子行收到“无法读取未定义的属性'length'的未定义属性”错误

app.js:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();
let data =[
  {id:1,type:"action"},
  {id:2,type:"comedy"}
];

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

index.js:

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

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Movies' });
});

module.exports = router;

1 个答案:

答案 0 :(得分:1)

尝试一下:

index.js:

let data =[
  {id:1,type:"action"},
  {id:2,type:"comedy"}
];

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Movies', data }); // you forgot passing the data array
})

另一个解决方案是:

app.js中,您可以这样做:

var app = express();
let data =[
  {id:1,type:"action"},
  {id:2,type:"comedy"}
];
app.locals.data = data; //added 

现在,您可以访问应用程序内呈现的模板中的局部变量,这意味着您无需在data方法中传递此render()