Pass a variable from javascript to ejs
Asked Answered
A

3

16

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:18

 >> 18|            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?

Alonzoaloof answered 3/6, 2016 at 14:14 Comment(8)
app.locals.myVar should work, provided that you set it in the correct place and use it correctly in your template. You should probably post more code.Rase
JS doesn't "pass" variables between files. Instead, all files are loaded and run in a global context (in a browser it's the window).Hatband
@robertklep:The problem is that it is undefined in the ejs file.I am not sure if I can use var express = require('express');var app = express(); also in the ejs file and if yes,if it will use the value from javascript file.Alonzoaloof
You can add it window object. that is accessible throughout application. Not sure whether it's available with express or not.Fijian
@HiteshKumar How will you add it to the window object from the server side? That's not how EJS templating works.Collins
Ok. I thought it is available in every javascript app. Thanks for clarification.Fijian
In node, instead of window, you literally have a variable called "global", but much the same way you wouldn't go appending data to the "window" object on the client side, you shouldn't be appending data to the "global" object on the server side.Davit
@Alonzoaloof posted a sustainable solution below — no globals.Davit
R
10

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>
<% } %>
Rase answered 3/6, 2016 at 14:38 Comment(7)
:Hmm..Can I ask you , if I also have res.render('index', { user : req.user, message: [] }); how can I write properly the 'index.ejs'?I mean , i am trying : app.get('/', function (req, res) { res.render('index', { user : req.user, message: [] }); res.render('index.ejs'); }); but it gives me some weird reference error in index.ejs although it works ok.Alonzoaloof
:Sorry to insist..In a few words I have 2 res.render statements in app.get('/').Even though it works , it gives me the reference error above.Can you let know if this is possible?Thanks..Alonzoaloof
@Alonzoaloof perhaps create a new question for this? Or is the error the same as you got before? If so, can you add the exact error that you're getting to your original question?Rase
@Alonzoaloof first: calling res.render() two times will not work. Second, I'm going to guess that req.user isn't defined, which would make the user variable inside the template undefined. This would point to an issue in your app that relates to authentication, and not so much templating.Rase
:But if I run it without the res.render('user_info.ejs' ) I receive absolute no errors about req.user.Is there a way to use the app.locals.myVar without putting it into render?Alonzoaloof
@Alonzoaloof but you're not declaring a variable named user when you render user_info.ejs, like you do with rendering index (the second argument, { user : req.user, ... }), so no wonder that you're getting a reference error about it.Rase
:Yes,you are right.The thing is how can I combine these 2 renders?something like.But I have 2 different files.Alonzoaloof
D
29

The app.locals.myVar approach should work, so something must be getting in the way. But you could avoid using app.locals.myVar altogether and pass variables directly to your views with:

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

app.get('/', function(req, res) {
    var myVar = 1;
    res.render('testPage', { myVar : myVar });
});

The myVar variable should now be available to the "testPage" ejs file. Inside of it you could do:

<%= myVar %>

And see it output "1".

Lastly, make sure you have set the view engine to ejs:

app.set('view engine', 'ejs');

Otherwise it won't work.

Davit answered 3/6, 2016 at 14:43 Comment(0)
R
10

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>
<% } %>
Rase answered 3/6, 2016 at 14:38 Comment(7)
:Hmm..Can I ask you , if I also have res.render('index', { user : req.user, message: [] }); how can I write properly the 'index.ejs'?I mean , i am trying : app.get('/', function (req, res) { res.render('index', { user : req.user, message: [] }); res.render('index.ejs'); }); but it gives me some weird reference error in index.ejs although it works ok.Alonzoaloof
:Sorry to insist..In a few words I have 2 res.render statements in app.get('/').Even though it works , it gives me the reference error above.Can you let know if this is possible?Thanks..Alonzoaloof
@Alonzoaloof perhaps create a new question for this? Or is the error the same as you got before? If so, can you add the exact error that you're getting to your original question?Rase
@Alonzoaloof first: calling res.render() two times will not work. Second, I'm going to guess that req.user isn't defined, which would make the user variable inside the template undefined. This would point to an issue in your app that relates to authentication, and not so much templating.Rase
:But if I run it without the res.render('user_info.ejs' ) I receive absolute no errors about req.user.Is there a way to use the app.locals.myVar without putting it into render?Alonzoaloof
@Alonzoaloof but you're not declaring a variable named user when you render user_info.ejs, like you do with rendering index (the second argument, { user : req.user, ... }), so no wonder that you're getting a reference error about it.Rase
:Yes,you are right.The thing is how can I combine these 2 renders?something like.But I have 2 different files.Alonzoaloof
M
0

Below code worked for me:

Inside app.js:

app.locals.myVar = myVar;

Inside home.ejs

<%= myVar %>
Mouthful answered 2/4, 2023 at 6:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.