4

I have 4 different routes in my routes>intro.js file, and want to pass same variable for each routes.

(I am using nodejs express with ejs view engine)

// 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});
}

It seems that there would be better way to pass common(something.common) variable to each routes(ejs view files), since something.common is being repeated.

Actually, the view file which receives that common variable is a common-used view file. That view file is included into the test1, test2, test3, test4 view file seperately, with using

<% include 'view_file' %>

Is there any way to pass that repeated variable to all routes at once?

Having some difficulties, any advice might really be appreciated.

Ry-
  • 218,210
  • 55
  • 464
  • 476
jwkoo
  • 2,393
  • 5
  • 22
  • 35

1 Answers1

3

I think what you are looking for is app.locals

In express 4, app.locals is treated as a global object.

app.locals = {
  something: {
    common: 'common'
}

From the post below:

These globals are passed as local variables to each view.

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

thomann061
  • 629
  • 3
  • 11