[英]Passing an Array to Jade/Pug Route in Express
I'm new to express and pug so forgive me if this is a noob question but how do I pass the array I created in one function to the route that will render the pug template. 我是新来表达和哈巴狗的人,所以如果这是一个菜鸟问题,请原谅我,但是我如何将在一个函数中创建的数组传递给将呈现哈巴狗模板的路由。 I ultimately want to loop though the array and render it as a table. 我最终想遍历数组并将其呈现为表。
My code - first I create the array from the data received from a file with the lodash map method. 我的代码-首先,我使用lodash map方法根据从文件接收的数据创建数组。 *EDIT - added full code structure - *编辑-添加了完整的代码结构-
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
console.log('Error: ' + err);
return;
}
var data = JSON.parse(data);
var newEventList = data.events.map(events => ({
id: events.id ,
name: events.name ,
venue: events.place.name ,
address: events.place.location.street + " " +
events.place.location.city + " " + events.place.location.zip ,
coverPicture: events.coverPicture ,
description: events.description ,
startTime: events.startTime ,
endTime: events.endTime
}));
});
So now I have an array of objects called newEventList. 所以现在我有了一个称为newEventList的对象数组。
My route for pug is 我去哈巴狗的路线是
app.get('/', function (req, res, newEventList) {
res.render('index', { title: 'Hey', message: 'Hello there!',
newEventList
})
})
I added title and message to test my pug template. 我添加了标题和消息来测试我的哈巴狗模板。 in my Pug Template I have 在我的哈巴狗模板中
h1= message
p= newEventList
but in the paragraph that is rendered I get a long error message - 但是在呈现的段落中,我收到了很长的错误消息-
function next(err) { // signal to exit route if (err && err === 'route') { return done(); } // signal to exit router if (err && err === 'router') { return done(err) } var layer = stack[idx++]; if (!layer) { return done(err); } if (layer.method && layer.method !== method) { return next(err); } if (err) { layer.handle_error(err, req, res, next); } else { layer.handle_request(req, res, next); } }
What am I doing wrong please? 请问我做错了什么?
From your route definition's callback, remove or rename newEventList
as your third param. 从路由定义的回调中,删除或重命名newEventList
作为第三个参数。
In your example, newEventList
is getting assigned to the done/next
callback. 在您的示例中, newEventList
被分配给done/next
回调。 Hence you're seeing a function being printed in your paragraph. 因此,您会看到一个函数正在您的段落中打印。
var newEventList = // Whatever value;
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!',
newEventList
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.