How to create global variables accessible in all views using Express / Node.JS?

前端 未结 8 1025
半阙折子戏
半阙折子戏 2020-11-28 01:53

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

相关标签:
8条回答
  • 2020-11-28 02:01

    you can also use "global"

    Example:

    declare like this :

      app.use(function(req,res,next){
          global.site_url = req.headers.host;   // hostname = 'localhost:8080'
          next();
       });
    

    Use like this: in any views or ejs file <% console.log(site_url); %>

    in js files console.log(site_url);

    0 讨论(0)
  • 2020-11-28 02:01

    With the differents answers, I implemented this code to use an external file JSON loaded in "app.locals"

    Parameters

    {
        "web": {
            "title" : "Le titre de ma Page",
            "cssFile" : "20200608_1018.css"
        }
    }
    

    Application

    var express     = require('express');
    var appli       = express();
    var serveur     = require('http').Server(appli);
    
    var myParams    = require('./include/my_params.json');
    var myFonctions = require('./include/my_fonctions.js');
    
    appli.locals = myParams;
    

    EJS Page

    <!DOCTYPE html>
    <html lang="fr">
    <head>
        <meta charset="UTF-8">
        <title><%= web.title %></title>
        <link rel="stylesheet" type="text/css" href="/css/<%= web.cssFile %>">
    </head>
    
    </body>
    </html>
    

    Hoping it will help

    0 讨论(0)
  • 2020-11-28 02:07

    For Express 4.0 I found that using application level variables works a little differently & Cory's answer did not work for me.

    From the docs: http://expressjs.com/en/api.html#app.locals

    I found that you could declare a global variable for the app in

    app.locals
    

    e.g

    app.locals.baseUrl = "http://www.google.com"
    

    And then in your application you can access these variables & in your express middleware you can access them in the req object as

    req.app.locals.baseUrl
    

    e.g.

    console.log(req.app.locals.baseUrl)
    //prints out http://www.google.com
    
    0 讨论(0)
  • 2020-11-28 02:09

    One way to do this by updating the app.locals variable for that app in app.js

    Set via following

    var app = express();
    app.locals.appName = "DRC on FHIR";
    

    Get / Access

    app.listen(3000, function () {
        console.log('[' + app.locals.appName + '] => app listening on port 3001!');
    });
    

    Elaborating with a screenshot from @RamRovi example with slight enhancement.

    0 讨论(0)
  • 2020-11-28 02:10

    In your app.js you need add something like this

    global.myvar = 100;
    

    Now, in all your files you want use this variable, you can just access it as myvar

    0 讨论(0)
  • 2020-11-28 02:17

    What I do in order to avoid having a polluted global scope is to create a script that I can include anywhere.

    // my-script.js
    const ActionsOverTime = require('@bigteam/node-aot').ActionsOverTime;
    const config = require('../../config/config').actionsOverTime;
    let aotInstance;
    
    (function () {
      if (!aotInstance) {
        console.log('Create new aot instance');
        aotInstance = ActionsOverTime.createActionOverTimeEmitter(config);
      }
    })();
    
    exports = aotInstance;
    

    Doing this will only create a new instance once and share that everywhere where the file is included. I am not sure if it is because the variable is cached or of it because of an internal reference mechanism for the application (that might include caching). Any comments on how node resolves this would be great.

    Maybe also read this to get the gist on how require works: http://fredkschott.com/post/2014/06/require-and-the-module-system/

    0 讨论(0)
提交回复
热议问题