在 Javascript 逻辑中访问 EJS 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11289793/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:18:28  来源:igfitidea点击:

Accessing EJS variable in Javascript logic

javascriptnode.jsexpressejs

提问by Catherine Hwang

I'm working on a Node.js app (it's a game). In this case, I have some code set up such that when a person visits the index and chooses a room, he gets redirected to the proper room.

我正在开发一个 Node.js 应用程序(这是一个游戏)。在这种情况下,我设置了一些代码,当一个人访问索引并选择一个房间时,他会被重定向到正确的房间。

Right now, it's being done like this with Express v2.5.8:

现在,它在 Express v2.5.8 中是这样完成的:

server.get("/room/:name/:roomId, function (req, res) {
  game = ~databaseLookup~
  res.render("board", { gameState : game.gameState });
}

Over in board.ejs I can access the gameState manner with code like this:

在 board.ejs 中,我可以使用如下代码访问 gameState 方式:

<% if (gameState) { %>
  <h2>I have a game state!</h2>
<% } %>

Is there a way for me to import this into my JavaScript logic? I want to be able to do something like var gs = ~import ejs gameState~and then be able to do whatever I want with it--access its variables, print it out to console for verification. Eventually, what I want to do with this gameState is to display the board properly, and to do that I'll need to do things like access the positions of the pieces and then display them properly on the screen.

有没有办法将它导入到我的 JavaScript 逻辑中?我希望能够做类似的事情var gs = ~import ejs gameState~,然后能够用它做任何我想做的事情——访问它的变量,将它打印到控制台进行验证。最后,我想用这个 gameState 做的是正确显示棋盘,为此我需要做一些事情,比如访问棋子的位置,然后在屏幕上正确地显示它们。

Thanks!

谢谢!

回答by Nick Hagianis

You could directly inject the gameState variable into javascript on the page.

您可以直接将 gameState 变量注入页面上的 javascript 中。

<% if (gameState) { %>
     <h2>I have a game state!</h2>
     <script>
        var clientGameState = <%= gameState %>            
     </script>
<% } %>

Another option might be to make an AJAX call back to the server once the page has already loaded, return the gameState JSON, and set clientGameState to the JSON response.

另一种选择可能是在页面加载后对服务器进行 AJAX 调用,返回 gameState JSON,并将 clientGameState 设置为 JSON 响应。

You may also be interested in this: How can I share code between Node.js and the browser?

您可能还对此感兴趣:如何在 Node.js 和浏览器之间共享代码?

回答by Ramaprasanna Chellamuthu

I feel that the below logic is better and it worked for me.

我觉得下面的逻辑更好,对我有用。

Assume the variable passed to the ejs page is uid, you can have the contents of the divtag or a htag with the variable passed. You can access the contents of the div or htag in the script and assign it to a variable.

假设传递给 ejs 页面的变量是uid,您可以拥有div标签的内容或h传递变量的标签。您可以访问h脚本中div 或标签的内容并将其分配给一个变量。

code sample below : (in ejs)

下面的代码示例:(在 ejs 中)

<script type="text/javascript">
    $(document).ready(function() {
        var x = $("#uid").html(); 
        alert(x);  // now JS variable 'x' has the uid that's passed from the node backend.
    });
</script>

<h2 style="display:none;" id="uid"><%=uid %></h2>

回答by Arootin Aghazaryan

I had the same problem. I needed to use the data not for just rendering the page, but in my js script. Because the page is just string when rendered, you have to turn the data in a string, then parse it again in js. In my case my data was a JSON array, so:

我有同样的问题。我不仅需要将数据用于渲染页面,还需要在我的 js 脚本中使用。因为页面在渲染的时候只是字符串,所以必须把数据转成字符串,然后在js中再次解析。在我的情况下,我的数据是一个 JSON 数组,所以:

<script>
  var test = '<%- JSON.stringify(sampleJsonData) %>'; // test is now a valid js object
</script>

Single quotes are there to not be mixed with double-quotes of stringify. Also from ejs docs:

单引号不能与 stringify 的双引号混合使用。同样来自 ejs 文档:

"<%- Outputs the unescaped value into the template"

"<%- 将未转义的值输出到模板中"

The same can be done for arrays. Just concat the array then split again.

对数组也可以这样做。只需连接数组然后再次拆分。

回答by kartik tyagi

In the EJS template:
ex:- testing.ejs

在 EJS 模板中:
例如:- testing.ejs

<html>
<!-- content -->
<script>
    // stringify the data passed from router to ejs (within the EJS template only)
    var parsed_data = <%- JSON.stringify(data) %>  
</script>
</html>

In the Server side script:
ex: Router.js

在服务器端脚本中:
例如:Router.js

res.render('/testing', {
    data: data // any data to be passed to ejs template
});

In the linked js (or jquery) script file:
ex:- script.js In JavaScript:

在链接的 js(或 jquery)脚本文件中:
例如:- script.js 在 JavaScript 中:

console.log(parsed_data)

In JQuery:

在 JQuery 中:

$(document).ready(function(){
    console.log(parsed_data)
 });

Note: 1. user - instead of = in <% %> tag
2. you can't declare or use data passed from router to view directly into the linked javascript or jquery script file directly.
3. declare the <% %> in the EJS template only and use it any linked script file.

注意: 1. user - 而不是 <% %> 标签中的 =
2. 你不能声明或使用从路由器传递来的数据直接查看链接的 javascript 或 jquery 脚本文件。
3. 仅在 EJS 模板中声明 <% %> 并在任何链接的脚本文件中使用它。

I'm not sure but I've found it to be the best practice to use passed data from router to view in a script file or script tag.

我不确定,但我发现使用从路由器传递的数据在脚本文件或脚本标签中查看是最佳实践。

回答by Raaj Kanchan

Well, in this case you can simply use input text to get data. It is easy and tested when you use it in firebase.

那么,在这种情况下,您可以简单地使用输入文本来获取数据。当您在 firebase 中使用它时,它很容易并经过测试。

<input type="text" id="getID" style="display: none" value="<%=id%>">