访问 Javascript 文件中传递的 EJS 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46539106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing passed EJS variable in Javascript file
提问by Rumba
RESTful routes js file:
RESTful 路由 js 文件:
// index route - show all todos
router.get("/", middleware.isLoggedIn,function(req,res) {
Todo.find({ "author.id" : req.user._id}, function(err, allTodos) {
if(err) {
console.log(err);
} else {
res.render("todo/index", {todos: allTodos});
}
});
});
My index.ejs file has:
我的 index.ejs 文件有:
<script src="/scripts/todoCalendar.js"></script>
at the end of the bodytag and I want to access the passed variable todosinside my todoCalendar.js file.
I tried putting
在body标签的末尾,我想访问todos我的 todoCalendar.js 文件中传递的变量。我试过放
<script>
var x= <%= todos %>
</script>
but it says xis undefined when i try to do a console.log(x)inside my todoCalendar.js file.
但是x当我尝试console.log(x)在我的 todoCalendar.js 文件中做一个时它说是未定义的。
Any help is greatly appreciated.
任何帮助是极大的赞赏。
回答by Mohimenul Joaa
Three way to solve the problem...
解决问题的三种方法...
variant
<script> var x = "<%= todos %>"; console.log(x); </script>variant
<script> var x = "<%- todos %>"; console.log(x); </script>variant [XD]
HTML:
<p id="yy" style="display:none"><%= todos %></p>Javascript:
<script> var x = document.getElementById("yy").innerText; console.log(x); </script>
变体
<script> var x = "<%= todos %>"; console.log(x); </script>变体
<script> var x = "<%- todos %>"; console.log(x); </script>变体 [XD]
HTML:
<p id="yy" style="display:none"><%= todos %></p>Javascript:
<script> var x = document.getElementById("yy").innerText; console.log(x); </script>
回答by TheRedstoneTaco
By formatting the html printing of the JSON you get from the server and using javascript (my case jQuery) to retrieve that text, store it, and remove it from the html :)
通过格式化您从服务器获得的 JSON 的 html 打印,并使用 javascript(我的案例 jQuery)来检索该文本、存储它并将其从 html 中删除:)
EJS:
EJS:
<span id='variableJSON' hidden>
<%= JSON.stringify(passedInEjsVariable); %>
</span>
JavaScript:
JavaScript:
var variableJSON = JSON.parse($('#variableJSON').text());
$('#variableJSON').remove();
回答by enhancedHyman
Only this works in my case. All versions with "" or with <%= fail.
只有这在我的情况下有效。所有带有 "" 或 <%= 的版本都失败。
<script>
var todos = <%-JSON.stringify(todos)%>;
for (var item of todos) {
console.log(item)
}
</script>
Thing to note: if using VS Codewith formatting on save for .ejs files, <%-gets split into <% -and you get Uncaught SyntaxError: Unexpected token ';'and what worked a second ago, suddenly stops working.
需要注意的事情:如果在保存 .ejs 文件时使用带有格式的VS Code,<%-会被拆分为<% -你会得到Uncaught SyntaxError: Unexpected token ';' 一秒钟前有效的方法突然停止工作。
回答by Chetan acharekar
http://ejs.co/says
- <% 'Scriptlet' tag, for control-flow, no output
- <%= Outputs the value into the template (HTML escaped)
- <%- Outputs the unescaped value into the template
- <%# Comment tag, no execution, no output
- <% 'Scriptlet' 标签,用于控制流,无输出
- <%= 将值输出到模板中(HTML 转义)
- <%- 将未转义的值输出到模板中
- <%# 注释标签,不执行,不输出
Can you try using <%- in ejs to read variable value?
您可以尝试在 ejs 中使用 <%- 来读取变量值吗?
回答by Mario Mazzola
I am afraid you can't use EJS tags inside a file with a .js extension.
恐怕您不能在扩展名为 .js 的文件中使用 EJS 标记。
If you put the js code at the bottom of the EJS document, there is no problem.
如果把js代码放在EJS文档的最下方,就没有问题了。
In the backend you do:
在后端,您执行以下操作:
res.render('todo/index', {todos: JSON.stringify(alltodos)});
In your ejs file you do:
在您的 ejs 文件中,您执行以下操作:
<script>
var x= <%- todos %>;
console.log(x);
</script>
This works fine. I ve just tested for my project.
这工作正常。我刚刚测试了我的项目。
If you want to use the same code inside a separate file with .js extension, it will not work. You get an 'unexpected token <' error in the browser console.
如果您想在带有 .js 扩展名的单独文件中使用相同的代码,它将不起作用。您在浏览器控制台中收到“意外令牌 <”错误。
The only option you have is to print todosinto a hidden DIV inside the ejs file and then get in through javascript (you can use innerText or innerHTML) and store it inside a variable. A bit hacky but it does the trick.
你唯一的选择是打印待办事项到EJS文件中隐藏的DIV,然后通过JavaScript获得(可以使用的innerText或innerHTML的),并将其存储在变量中。有点hacky,但它确实有效。

