I want to use a variable which is declared in javascript file to a ejs file.
javascript:
var express = require(\'express\');
var app = express();
va
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>
<% } %>
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.