问题
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