简体   繁体   English

如何将app.js中的公共变量渲染到express中的所有路径

[英]how to render common variables from app.js to all routes in express

In my Node.js application some variables that render or every route are common.There are around 4-5 variables which render on every route. 在我的Node.js应用程序中,一些渲染变量或每个路径都是常见的。每个路径上有大约4-5个变量。 And I have around 20 routes. 我有大约20条路线。

Currently I am doing passing those variables in every route in res.render 目前我正在res.render中的每个路由传递这些变量

Is there a method by which I can pass these common variables in some place '(eg:app.js)` which is being used by every route, so that I can clean up my code a bit. 有没有一种方法可以在某些地方传递这些公共变量'(例如:app.js)`,每个路由都在使用它,这样我就可以清理一下我的代码了。

I use express.js for node and handlebars for template. 我使用express.js作为模板的节点和handlebars

EDIT:I think I should explain a bit more 编辑:我想我应该多解释一下

res.render('abc', {
                        commonitem1: 'one',
                        commonitem2: 'two',
                        ...
                   });

-------------------------------------
another route
res.render('xyz', {
                        commonitem1: 'one',
                        commonitem2: 'two',
                        ...
                   });

I want to avoid this repeating in my every routes and want to render it from a common place. 我希望避免在我的每条路线中重复这种情况,并希望从一个普通的地方渲染它。

For session or request dependent values you can store those common values in a global variable and then use them directly in res.render. 对于会话或请求相关值,您可以将这些公共值存储在全局变量中,然后直接在res.render中使用它们。 To do that you have following options 为此,您有以下选项

  • Use app.use to store values : 使用app.use存储值:

In your app.js add a middleware which does this for you. 在你的app.js中添加一个中间件,为你做这件事。 Remember to write this middleware before any other routes you define because middleware functions are executed sequentially. 请记住在您定义的任何其他路由之前编写此中间件,因为中间件函数是按顺序执行的。

app.use(function(req, res, next){
    res.locals.items = "Value";
    next();
});
//your routes follow
app.use(‘/’, home);

In your routes you can place items directly in res.render like: 在您的路线中,您可以将items直接放在res.render中,例如:

res.render('layout', {title: 'My awesome title',view: 'home', item :res.locals.items });
  • Use express-session to store values : 使用express-session存储值:

If you have express-session installed you can save some data in req.session.item and place them in any route like: 如果你安装了快速会话,你可以在req.session.item保存一些数据并将它们放在任何路由中,如:

res.render('layout', {title: 'My awesome title',view: 'home', item :req.session.items });

It seems that res.locals is what you are looking for - this object is passed to your views for every request and is scoped to each individual request (ie each request can have its own version of res.locals ). 似乎res.locals是您正在寻找的 - 这个对象被传递给您的每个请求的视图,并且作用于每个单独的请求(即每个请求可以有自己的res.locals版本)。 There is also app.locals which is shared for all requests. 还有app.locals ,它为所有请求共享。

I do not have practical experience with this, but you can either use this object to pass all variables to your views or perhaps Express will merge whatever is in app.locals with res.locals and what you send to the view via res.render() . 我没有这方面的实际经验,但您可以使用此对象将所有变量传递给您的视图,或者Express可以将app.locals任何app.localsres.locals合并以及您通过res.render()发送到视图的res.render() Please test carefully, I have not found relevant information about the merging behaviour in the official docs. 请仔细测试,我没有在官方文档中找到有关合并行为的相关信息。

As for populating the res.locals , to keep the code DRY , you can write a custom middleware that populates the object with whatever you need it to have before your actual route logic is executed. 至于填充res.locals ,为了保持代码DRY ,您可以编写一个自定义中间件 ,在您执行实际路由逻辑之前,使用您需要的任何内容来填充对象。

// I created common func for all routes as below.

function commonRes(layout, req, res) {

  if (req.session.user) {
    res.render(layout, {
      user: req.session.user
      //csrfToken: req.csrfToken() // csrf 
    })

  } else {
    res.render(layout, {
      user: null,
      csrfToken: null
    })
  }

  return res.end()
}



// and apply it to all routes simply as below



app.get('/', (req, res) => {

  return commonRes('index.html', req, res)

})

app.get('/new', (req, res) => {

  return commonRes('new.html', req, res)
})

You can create one constants.js file with below code 您可以使用以下代码创建一个constants.js文件

(function (constants) {
    var FetchDataErrorMessage = "Error while fetching User Data";
    var ConnectionErroMessage = "Error while fetching Connecting Server";
    var InsertDataErrorMessage = "Error while inserting User Data";
    var RemoveDataErrorMessage = "Error while removing User Data";
    var UpdateDataErrorMessage = "Error while updating User Data";
})(module.exports);

In any file where you need to use those variables you can add below code. 在您需要使用这些变量的任何文件中,您可以添加以下代码。

var constants = require('constants');    
console.write(constants.RemoveDataErrorMessage);   

Output :- "Error while removing User Data" 输出: - “删除用户数据时出错”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM