我的 routes>intro.js 文件中有 4 条不同的路由,我想为每条路由传递相同的变量。
(我正在使用带有 ejs View 引擎的 nodejs express)
// intro.js file
var something = {
common: 'common',
different: {
test1: 'test1',
test2: 'test2',
test3: 'test3',
test4: 'test4'
}
}
router.get('/test1', (req, res) => {
res.render('test1', {common: something.common, different: something.different.test1});
}
router.get('/test2', (req, res) => {
res.render('test2', {common: something.common, different: something.different.test2});
}
router.get('/test3', (req, res) => {
res.render('test3', {common: something.common, different: something.different.test3});
}
router.get('/test4', (req, res) => {
res.render('test4', {common: something.common, different: something.different.test4});
}
似乎有更好的方法将 common(something.common) 变量传递给每个路由(ejs View 文件),因为 something.common 被重复了。
实际上,接收公共(public)变量的 View 文件是一个常用的 View 文件。该 View 文件分别包含到 test1、test2、test3、test4 View 文件中,使用
<% include 'view_file' %>
有什么方法可以将那个重复的变量一次传递给所有路由吗?
有一些困难,任何建议可能真的很感激。
最佳答案
我想你要找的是app.locals
在 express 4 中,app.locals 被视为全局对象。
app.locals = {
something: {
common: 'common'
}
来自下面的帖子:
These globals are passed as local variables to each view.
更多信息:How to create global variables accessible in all views using Express / Node.JS?
关于node.js - nodejs ejs View 引擎,一次将相同的参数传递给不同的路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49066049/