admin管理员组

文章数量:1391975

This is probably a stupid question, but in Express, when you define local variables in res.render(view, {variable: variable}), how are they accessed on the frontend? Where are they kept? When I try to access a variable I defined through this method with console.log(variable) Firebug throws an error saying that variable is not defined. I also tried console.log(window.variable), with similar results. So where are these variables kept?

Also, are res.locals variables kept in the same place, or are they just thrown out? These variables are accessible to templating engines like swig and jade, but I could not find them using console.log() either.

This is probably a stupid question, but in Express, when you define local variables in res.render(view, {variable: variable}), how are they accessed on the frontend? Where are they kept? When I try to access a variable I defined through this method with console.log(variable) Firebug throws an error saying that variable is not defined. I also tried console.log(window.variable), with similar results. So where are these variables kept?

Also, are res.locals variables kept in the same place, or are they just thrown out? These variables are accessible to templating engines like swig and jade, but I could not find them using console.log() either.

Share Improve this question asked Oct 1, 2014 at 4:02 trysistrysis 8,46619 gold badges53 silver badges88 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

These variables are not passed automatically to client-side code; as you say, they're available to code in your view templates. Similarly, and variables defined in res.locals (or app.locals, which has the same API) will be available as local variables in any views.

If you want to make them available to client side code, you'd have to manually send them as part of the response, in a form accessible to the client-side JavaScript. For instance, you could write them to a <script> tag, as is done here: Accessing Express.js local variables in client side JavaScript .

These variables are used for rendering the view on the server side only. Obviously some of these values make their way into the HTML of the server side response, but you probably want to look at a module such as sharify if you want to serialize these to JSON, embed into a <script> tag in the HTML, and get access to them in the browser javascript code.

本文标签: javascriptresrender() Locals Location on FrontendStack Overflow