【问题标题】:Error rendering list with Pug and ExpressJS使用 Pug 和 ExpressJS 渲染列表时出错
【发布时间】:2018-11-15 02:42:43
【问题描述】:

你好,我对 Node、express 和 pug 还很陌生我正在使用 pugcli,当它尝试渲染 html 时出现错误。

pugcli 错误在终端上显示为:

无法读取未定义的属性“长度”

这很奇怪,因为当我尝试在浏览器中查看它时,即使 pug cli 显示错误,浏览器也会显示一个列表,但所有 <li> 元素都是空的。

我希望 <li> 显示对象 ID、名称和年龄

我知道在 pug 中,为了渲染一个对象,您必须使用某种 for 循环来遍历它。我已经在 pug 文件中写了它,但是对象没有渲染。

如果我在代码中遗漏了什么,或者我是否完全搞砸了代码,我将不胜感激?

我的设置如下

bin/www
public
   javascripts
   stylesheets
routes
   index.js
views
   index.pug
   layout.pug
   ...
app.js

我的 index.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.js 是:

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;

而我的 app.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;

【问题讨论】:

  • 欢迎来到 StackOverflow 我希望我们可以帮助您找到您想要的答案。将!{JSON.stringify(users)} 放入模板时会显示什么?
  • @JuanD.Gómez 谢谢你的帮助。我试着玩 json.stringify。我在 pug 文件中添加了!{JSON.stringify(users)},它在渲染或页面中创建了一个错误。它不喜欢 pug 文件中的代码。我在 js 文件中尝试了它,它没有做任何事情。我进一步玩了 ti,它把物体变成了一根弦。我不能再拨打users.id 之类的电话并获取ID。它变成了一个完整的字符串,我必须完全解析。这是行不通的。如果有任何其他帮助,我将不胜感激。
  • @Graham 感谢您的建议,但我尝试按照您的建议扩展代码,但它没有做任何事情,我还取出了除用户之外的变量,问题仍然存在。我确实发现错误 Cannot read property 'length' of undefined 来自 index.pug 中的第 9 行,该行是for user, i in users。感谢您的帮助。
  • 您的其他变量是否正在传递给模板?我的意思是,您可以访问您在模板中传递的其他变量吗?使用!{JSON.stringify(users)} 的目的是调试并检查用户数组是否正确传递。因此,您不必将此代码保留在模板中,只需检查值是否正确,然后将其删除即可。
  • 我投票结束这个问题,因为它是由于一个小的印刷错误(users vs. user)。

标签: node.js express pug


【解决方案1】:

看来还是打错了:

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(迭代对象)。我已经在我的机器上尝试了代码,并且工作正常。

【讨论】:

  • 感谢您的回答我对此比较陌生,我对需要调用哪个项目感到困惑。我现在看得更清楚了!!!!感谢社区谢谢大家
猜你喜欢
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 1970-01-01
  • 2017-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
相关资源
最近更新 更多