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

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

问题描述

我正在使用一个NodeJS应用程序(这是一个游戏)。在这种情况下,我有一些代码设置,使得当一个人访问索引并选择一个房间时,他被重定向到适当的房间。

I'm working on a NodeJS 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〜

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~

可以使用它来做任何事情 - 访问它的变量,将其打印出来进行控制以进行验证。最终我想用这个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 pieces and then display them properly on the screen.

谢谢!

推荐答案

你可以直接注入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和浏览器之间共享代码?

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

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

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