如何使用 Express/Node.JS 创建可在所有视图中访问的全局变量? [英] How to create global variables accessible in all views using Express / Node.JS?

查看:46
本文介绍了如何使用 Express/Node.JS 创建可在所有视图中访问的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我使用 Jekyll 建立了一个博客,您可以在文件 _config.yml 中定义变量可在所有模板/布局中访问.我目前正在使用 Node.JS/ExpressEJS 模板和 ejs-locals(用于局部/布局. 如果有人熟悉 Jekyll,我希望做一些类似于 site.title 的全局变量,例如 _config.yml 中的 site.title.我有类似站点的变量标题,(而不是页面标题),作者/公司名称,在我的所有页面上都保持不变.

Ok, so I have built a blog using Jekyll and you can define variables in a file _config.yml which are accessible in all of the templates/layouts. I am currently using Node.JS / Express with EJS templates and ejs-locals (for partials/layouts. I am looking to do something similar to the global variables like site.title that are found in _config.yml if anyone is familiar with Jekyll. I have variables like the site's title, (rather than page title), author/company name, which stay the same on all of my pages.

这是我目前正在做的一个例子.:

Here is an example of what I am currently doing.:

exports.index = function(req, res){
    res.render('index', { 
        siteTitle: 'My Website Title',
        pageTitle: 'The Root Splash Page',
        author: 'Cory Gross',
        description: 'My app description',
        indexSpecificData: someData
    });
};

exports.home = function (req, res) {
    res.render('home', {
        siteTitle: 'My Website Title',
        pageTitle: 'The Home Page',
        author: 'Cory Gross',
        description: 'My app description',
        homeSpecificData: someOtherData
    });
};

我希望能够在一个地方定义变量,如我的网站的标题、描述、作者等,并通过 EJS 在我的布局/模板中访问它们,而不必将它们作为选项传递给每次调用 res.render.有没有办法做到这一点,并且仍然允许我传入特定于每个页面的其他变量?

I would like to be able to define variables like my site's title, description, author, etc in one place and have them accessible in my layouts/templates through EJS without having to pass them as options to each call to res.render. Is there a way to do this and still allow me to pass in other variables specific to each page?

推荐答案

有机会学习Express 3 API Reference 我发现了我想要的东西.特别是 app.locals 然后再往下一点res.locals 包含了我需要的答案.

After having a chance to study the Express 3 API Reference a bit more I discovered what I was looking for. Specifically the entries for app.locals and then a bit farther down res.locals held the answers I needed.

我自己发现函数 app.locals 接受一个对象并将其所有属性存储为应用程序范围内的全局变量.这些全局变量作为局部变量传递给每个视图.但是,res.locals 函数的范围仅限于请求,因此,响应局部变量只能在该特定请求/响应期间呈现的视图中访问.

I discovered for myself that the function app.locals takes an object and stores all of its properties as global variables scoped to the application. These globals are passed as local variables to each view. The function res.locals, however, is scoped to the request and thus, response local variables are accessible only to the view(s) rendered during that particular request/response.

所以在我的 app.js 中,我所做的是添加:

So for my case in my app.js what I did was add:

app.locals({
    site: {
        title: 'ExpressBootstrapEJS',
        description: 'A boilerplate for a simple web application with a Node.JS and Express backend, with an EJS template with using Twitter Bootstrap.'
    },
    author: {
        name: 'Cory Gross',
        contact: 'CoryG89@gmail.com'
    }
});

然后所有这些变量在我的视图中都可以作为 site.titlesite.descriptionauthor.name 访问作者.联系方式.

Then all of these variables are accessible in my views as site.title, site.description, author.name, author.contact.

我还可以使用 res.locals 为请求的每个响应定义局部变量,或者简单地将页面标题等变量作为 options 参数传入 代码>渲染调用.

I could also define local variables for each response to a request with res.locals, or simply pass variables like the page's title in as the optionsparameter in the render call.

此方法将不允许允许您在中间件中使用这些本地变量.正如 Pickels 在下面的评论中所建议的那样,我确实遇到了这个问题.在这种情况下,您将需要在他的替代(和赞赏)答案中创建一个中间件功能.您的中间件函数需要为每个响应将它们添加到 res.locals 中,然后调用 next.这个中间件函数需要放在任何其他需要使用这些局部变量的中间件之上.

This method will not allow you to use these locals in your middleware. I actually did run into this as Pickels suggests in the comment below. In this case you will need to create a middleware function as such in his alternative (and appreciated) answer. Your middleware function will need to add them to res.locals for each response and then call next. This middleware function will need to be placed above any other middleware which needs to use these locals.

通过app.localsres.locals 声明locals 的另一个区别是app.locals代码> 变量设置一次并在应用程序的整个生命周期中持续存在.当您在中间件中使用 res.locals 设置 locals 时,每次收到请求时都会设置这些.您基本上应该更喜欢通过 app.locals 设置全局变量,除非该值取决于传递给中间件的请求 req 变量.如果值没有改变,那么在 app.locals 中只设置一次会更有效.

Another difference between declaring locals via app.locals and res.locals is that with app.locals the variables are set a single time and persist throughout the life of the application. When you set locals with res.locals in your middleware, these are set everytime you get a request. You should basically prefer setting globals via app.locals unless the value depends on the request req variable passed into the middleware. If the value doesn't change then it will be more efficient for it to be set just once in app.locals.

这篇关于如何使用 Express/Node.JS 创建可在所有视图中访问的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆