Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

node.js - 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: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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...