Pug iteration: Cannot read property 'length' of undefined

假如想象 提交于 2021-01-27 12:15:17

问题


I am having the following data in js file:

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

and trying to print it using pug template

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

I get the error as "Cannot read property 'length' of undefined" at the each post line

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:


Try this:

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
})

Another solution is:

In the app.js, you could do this:

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

Now you can access local variables in templates rendered within the application which mean you don't need to pass this data in the render() method



来源:https://stackoverflow.com/questions/52606235/pug-iteration-cannot-read-property-length-of-undefined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!