[英]Pass array to routes/index.js from app.js in Nodejs with Express 4
How can I pass an array of objects to the routes middle-ware so that I can render the view depending on the variables passed. 如何将对象数组传递给路由中间件,以便可以根据传递的变量来呈现视图。
Currently, this is the layout I am working with 目前,这是我正在使用的布局
app.js app.js
var index = require('./routes/index');
ARRAY = [objects];
app.use('/', index);
routes/index.js 路线/ index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next){
res.render('index', {data: ARRAY});
});
module.exports = router;
index.jade index.jade
extends layout
block content
each d in data
div!= d.method()
Currently the only solution I can produce that actually works is to use global variables, but this is not sustainable or scalable. 目前,我能产生的唯一可行的解决方案是使用全局变量,但这不是可持续的或可扩展的。 I have tried app.set('shrinkr', shrinkr);
我已经尝试过app.set('shrinkr',收缩器); and app.locals but cannot get either of these to work with the layout of my app.
和app.locals,但无法使它们与我的应用布局配合使用。 From my understanding of the Express4 framework I should be able to do something like this in app.js:
从对Express4框架的了解中,我应该能够在app.js中执行以下操作:
var index = require('./routes/index')(array);
but I cannot get the implementation correct, and there is no info about this on the web. 但我无法正确实现,网络上也没有有关此信息。
There are multiple ways that you can tackle this, but if you want to "bake" the array into the middleware (as your code sample suggested), you can do this: 您可以通过多种方法来解决此问题,但是,如果要将数组“烘焙”到中间件中(如代码示例所建议的那样),可以执行以下操作:
var express = require('express');
module.exports = function(array) {
var router = express.Router();
return router.get('/', function(req, res, next){
res.render('index', {data: array});
});
}
Then you can use it as you suggested: 然后,您可以按照建议使用它:
var index = require('./routes/index')(array);
Because new middleware is created every time you invoke the exported function, you can bake independent arrays into different middleware: 由于每次调用导出的函数时都会创建新的中间件,因此可以将独立的数组烘焙到不同的中间件中:
var index1 = require('./routes/index')(["array 1"]);
var index2 = require('./routes/index')(["array 2"]);
Which may or may not be useful to you, depending on your needs. 根据您的需求,这可能对您有用或无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.