将变量从javascript传递给ejs [英] Pass a variable from javascript to ejs
问题描述
我想使用在javascript文件中声明的变量到ejs文件。
I want to use a variable which is declared in javascript file to a ejs file.
javascript:
javascript:
var express = require('express');
var app = express();
var myVar = 1;
在ejs文件中,我想在几个if语句中使用该变量,我必须再次声明它以便能够使用它。
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 ) ....
我怎样才能避免这种情况?或者是有没有办法创建一个可以从javascript和ejs访问的配置文件?
How can I avoid this?Or is there a way for creating a configuration file which is accesible from both javascript and ejs?
我还尝试使用:
app.locals.myVar = 1
但在ejs文件中未定义。
but it is undefined in the ejs file.
-------更新--------------------------
------- UPDATE --------------------------
在我使用的代码中:
app.get('/', function (req, res) {
res.render('index', { user : req.user, message: [] });
});
:
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)
.....
哪个没有,因为我说代码运行正常。如果我运行它而没有添加第二个 res.render('user_info.ejs)
我没有收到错误。
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.
那么,我可以有两个res.render语句吗?
So, can I have two res.render statements?
推荐答案
这是一个关于如何使用 app.locals
将变量暴露给(EJS)模板的一个非常简单的例子:
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>
<% } %>
这篇关于将变量从javascript传递给ejs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!