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!
9 Answers
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?
11I 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.
4I 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><%=uid %></h2> 1 In the EJS template:
ex:- 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
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:
console.log(parsed_data)In 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.
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.
This works for me.
// bar chart data var label = '<%- JSON.stringify(bowlers) %>'; var dataset = '<%- JSON.stringify(data) %>'; var barData = { labels: JSON.parse(label), datasets: JSON.parse(dataset) } 0 This should work
res.render("board", { gameState : game.gameState });in frontend js
const gameState = '<%- JSON.stringify(gameState) %>' You can assign backend js to front end ejs by making the backend js as a string.
<script> var testVar = '<%= backEnd_Var%>';
</script> 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" value="<%=id%>"> I know this was answered a long time ago but thought I would add to it since I ran into a similar issue that required a different solution.
Essentially I was trying to access an EJS variable that was an array of JSON objects through javascript logic like so:
<script> // obj is the ejs variable that contains JSON objects from the backend var data = '<%= obj %>';
</script>When I would then try and use forEach() on data I would get errors, which was because '<%= obj %>' provides a string, not an object.
To solve this:
<script> var data = <%- obj %>;
</script>After removing the string wrapping and changing to <%- (so as to not escape html going to the buffer) I could access the object and loop through it using forEach()