Accessing EJS variable in Javascript logic

ejs pass object to javascript
ejs variables
ejs-locals
pass node js variable to javascript
ejs foreach is not a function
javascript access express variable
express-ejs layout
ejs get data from 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.

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 });
}

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

<% 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.

Thanks!

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>
<% } %>

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.

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

EJS -- Embedded JavaScript templates, EJS is used in node.js when working with the Express framework as a add a bit of logic that will check if the value of the variable is JavaScript  Accessing EJS variable in Javascript logic. Questions: 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. Right now it’s being done like this, with Express v2.5.8:

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 div tag or a h tag with the variable passed. You can access the contents of the div or h tag in the script and assign it to a variable.

code sample below : (in 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>

Getting started with EJS - Vanessa Ating, https://stackoverflow.com/questions/11289793/accessing-ejs-variable-in-​javascript-logic this thread should probably have the answer. Edit: sorry meant to reply  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.

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

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

Passing data from node.js to ejs file, but using the data in an , Use <%= %> to embed the return value of a Javascript expression in HTML. Render an EJS template from an Express handler using resp.render(); Pass In this hyptothetical template format, variables and logic are defined by With that we get access to a new function available on our response object  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 div tag or a h tag with the variable passed. You can access the contents of the div or h tag in the script and assign it to a variable. code sample below : (in ejs)

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:

<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:

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

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

Pass data from app.js to the <script> in ejs file : node, using the body-parser middleware and JavaScript logic in EJS files. The area of my index.js file in which I've created all my variables to tell  Accès à la variable EJS dans la logique Javascript je travaille sur une application NodeJS (c'est un jeu). Dans ce cas, j'ai mis en place un code tel que lorsqu'une personne visite l'index et choisit une chambre, elle est redirigée vers la chambre appropriée.

Using Ejs In Express, Just like normal JavaScript, EJS can read assigned value to variables on the server and render them in the template. Take Note! You should have  Access to variables inside EJS. EJS exists to, with JS-based logic support, inject plain text into other plain text: you can't template in a true JS object and

Node.js Tutorial for Beginners (Part 3): Transferring Data Between , I want to put logic and data into object in external .js file, include that file to script.js') The jade variable type can now be accessed in script.js using the  1) You can pass an ejs variable value to a Javascript variable simply create an ejs variable and assign the value inside the script tag to the var getTest Ex: var getTest = <%= test %>; 2) You can't pass an javascript variable value to a ejs variable

EJS Variables (Injecting Values), js with MongoDB and Mongoose, which can be friendly to missing fields, if only there were an easy way to avoid the “undefined” value when  EJS Variables: In this tutorial, we are going to learn about the EJS variable (injecting values) with examples. Submitted by Godwill Tetah, on July 08, 2019 Hi! Welcome to NODE AND EJS TEMPLATE ENGINE SERIES. Today, we will talk about EJS variables or how we can inject values?

Comments
  • I've decided to roll with the AJAX call once the page has already loaded. The problem with your code above is that <%= gameState %> evaluates to [object Object] which is not at all what I want. Thanks!
  • I use <% include script %> at the bottom of all my pages that has some standard stuff passed to it, like request object, user object, form errors.
  • if the code evaluates to [object Object], I suggest using JSON.stringify(game.gameState) server side. Then the stringified object will be put into the script tag. Since the ejs rendering normally escapes special characters for HTML, you'll want to use var clientGameState = <%- gameState %> within the script tag (instead of <%= ) If you need the gameState for rendering the page as well, you can do a JSON.parse() to loop over it etc.
  • Following @Matthias here's how I did it: res.render('test', { images: JSON.stringify(images) }) on server side, var test = JSON.parse('<%- images %>'); on client side.
  • @Matthias How would I use the JSON.stringify method if the object contained user generated content? AKA how would I protect against injection attacks?
  • with the above code, you can easily see the entire UID object when you do view source. This is not the right approach even though it works