你好,我对Node,Expression和Pug还是陌生的,我正在尝试将对象渲染到视图中,但是我收到一个Pug错误,或者至少我认为这是Pug错误。我正在使用pugcli,当它尝试呈现html时出现错误。
pugcli错误在终端上显示为:
无法读取未定义的属性“长度”
这很奇怪,因为即使pug cli显示错误,当我尝试在浏览器中查看它时,浏览器也会显示一个列表,但所有<li>
元素都为空。
我希望bin/www
public
javascripts
stylesheets
routes
index.js
views
index.pug
layout.pug
...
app.js
显示对象的ID,名称和年龄
我知道在pug中,为了渲染对象,您必须使用某种for循环遍历该对象。我已经在pug文件中编写了该文件,但是对象未渲染。
如果我在代码中缺少什么,或者如果我完全弄乱了代码,我将不胜感激?
我的设置如下
extends layout block content h1= title p Welcome to #{appHeading} div ul for user, i in users li= users.name +" - "+ users.id li=number
我的index.pug是:
var express = require('express');
var router = express.Router();
var users = [
{
id: 0,
name: 'Glenn',
age: 40
},
{
id: 1,
name: 'Jeff',
age: 37
},
{
id: 2,
name: 'Sara',
age: 22
},
{
id: 3,
name: 'Bill',
age: 41
},
{
id: 4,
name: 'Mary',
age: 29
},
];
var appHeading = 'my object render app '
var number = 42;
/* GET home page. */
router.get('/', function(req, res, next) {
//res.json(users);
//res.send('Is this working?')
res.render('index', {
title: 'This is my app to render objects in pug',
users,
number,
appHeading
});
});
module.exports = router;
这是我的index.js:
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const bodyParser = require('body-parser');
const indexRouter = require('./routes/index.js');
const usersRouter = require('./routes/users.js');
const app = express();
/*const logging = function(req, res, next){
console.log('Logging....')
next();
}
*/
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
//Body Parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : false}));
//app.use(express.json());
//app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//app.use(logging);
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');
});
app.listen(port=3000 , function(){
console.log('Server started on port '+ port);
})
module.exports = app;
我的app.js是:
{{1}}
答案 0 :(得分:0)
似乎毕竟是错字:
extends layout
block content
h1= title
p Welcome to #{appHeading}
div
ul
for user, i in users
li= user.name +" - "+ user.id
li=number
这将起作用。发生的事情是您正在访问users
(数组)而不是user
(迭代对象)。我已经在机器上尝试过该代码,并且可以正常工作。