在 Javascript 逻辑中访问 EJS 变量 [英] Accessing EJS variable in Javascript logic

查看:28
本文介绍了在 Javascript 逻辑中访问 EJS 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

现在,Express v2.5.8 就是这样做的:

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

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

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

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

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

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

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中注入gameState变量.

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

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

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

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.

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

这篇关于在 Javascript 逻辑中访问 EJS 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆