George George - 6 months ago 78
Node.js Question

Pass a variable from javascript to ejs

I want to use a variable which is declared in javascript file to a ejs file.

javascript:

var express = require('express');
var app = express();

var myVar = 1;


In the ejs file , where I want to use that variable inside a few if statements ,I have to declare it again in order to be able to use it.

ejs file:

var myVar = 1;
if ( my Var ) ....


How can I avoid this?Or is there a way for creating a configuration file which is accesible from both javascript and ejs?

I tried also to use:

app.locals.myVar = 1


but it is undefined in the ejs file.

------- UPDATE --------------------------

In my code I am using:

app.get('/', function (req, res) {
res.render('index', { user : req.user, message: [] });

});


after using the app.locals:

app.get('/', function (req, res) {

res.render('index', { user : req.user, message: [] });
res.render('user_info.ejs');


});

and even though the code runs fine , I am receiving:

ReferenceError: ....user_info.ejs:38

>> 38| height:60px;


user is not defined
at eval (eval at <anonymous> (...node_modules/ejs/lib/ejs.js:464:12), <anonymous>:20:12)

at returnedFn (...node_modules/ejs/lib/ejs.js:493:17)
at View.exports.renderFile [as engine] (.../node_modules/ejs/lib/ejs.js:350:31)
.....


which doesn't make sence ,since as I said the code runs fine.And If I run it without the addition of the second
res.render('user_info.ejs)
I receive no errors.

So, can I have two res.render statements?

Answer

Here's a very simple example on how app.locals can be used to expose variables to (EJS) templates:

// app.js
var express = require('express');
var app     = express();
var server  = app.listen(3000);

app.locals.myVar = 1;

app.get('/', function(req, res) {
  res.render('index.ejs');
});

// views/index.ejs
<% if (myVar) { %>
  <h1>myVar is here!</h1>
<% } else { %>
  <h1>Boohiss no myVar!</h1>
<% } %>