在名为controllers.js
的文件中,我有这些变量:
var indexCtrl = require('./index'),
offerCtrl = require('./offer'),
setLocaleCtrl = require('./setLocale'),
specificationsCtrl = require('./specifications');
和这个对象:
var routes = {
indexCtrl: {
'fr-FR' : '/accueil',
'en-EN' : '/home',
'de-DE' : '/startseite'
},
offerCtrl: {
'fr-FR' : '/offre',
'en-EN' : '/offer',
'de-DE' : '/angebot'
},
setLocaleCtrl: {
'fr-FR' : '/setLocale/:locale',
'en-EN' : '/setLocale/:locale',
'de-DE' : '/setLocale/:locale'
},
specificationsCtrl: {
'fr-FR' : '/specifications',
'en-EN' : '/specifications-en',
'de-DE' : '/spezifikationen'
}
};
例如,所需的index.js:
'use strict';
var IndexModel = require('../models/index');
exports.route = function(req, res, locale) {
console.log(locale);
var model = new IndexModel();
res.render('index', model);
};
如何使用var route
中定义的indexCtrl作为上面定义的indexCtrl(带有require)?
编辑: 例如:
for (var ctrl in routes) {
var ctrlContent = routes[ctrl];
for (var language in ctrlContent) {
var route = ctrlContent[language];
//router.get(route, ctrl);
console.log('%s, %s, %s', ctrl, language, route);
}
}
日志显示:
indexCtrl, fr-FR, /accueil
indexCtrl, en-EN, /home
indexCtrl, de-DE, /startseite
offerCtrl, fr-FR, /offre
offerCtrl, en-EN, /offer
offerCtrl, de-DE, /angebot
setLocaleCtrl, fr-FR, /setLocale/:locale
setLocaleCtrl, en-EN, /setLocale/:locale
setLocaleCtrl, de-DE, /setLocale/:locale
specificationsCtrl, fr-FR, /specifications
specificationsCtrl, en-EN, /specifications-en
specificationsCtrl, de-DE, /spezifikationen
这样,我知道路由/accueil
必须由控制器indexCtrl在语言环境fr-FR中呈现。但是如果我尝试使用ctrl.route
- 例如在require中定义的indexCtrl.route-,我会收到错误:Route.get() requires callback functions but got a [object Undefined]
。
答案 0 :(得分:0)
看看你的问题,这可能会解决问题:
var indexCtrl = require(routes.indexCtrl[language]),
offerCtrl = require(routes.offerCtrl[language]),
setLocaleCtrl = require(routes.setLocaleCtrl[language]),
specificationsCtrl = require(routes.specificationsCtrl[language]);