Accessing EJS variable in Javascript logic
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?
Accessing EJS variable on script tag
What you are doing here is actually called includes
, which is for partials in EJS.
<script> const coffepoints = <% - JSON.stringify(campgrounds) %></script>
^^^
You want to display, or output an EJS variable. So, you would use <%=
tag.
<script> const coffepoints = <%= JSON.stringify(campgrounds) %></script>
You can view the EJS documentation here, which includes all the available tags in EJS.
Javascript accessing ejs variable in Node.js context
Seems like you need some quotes.
Try
var name = '<%= data %>';
How can I access an Express app.locals variable from within a client-side Javascript file?
Just in case anyone finds themselves here, what I was looking for was the following:
<script src="/javascripts/search.js" currentUserId=<%= currentUser._id %> currentUserName=<%= currentUser.username %>></script>
Related Topics
How to Find Middle Element of Array in JavaScript
Convert JavaScript Date Format to Yyyy-Mm-Ddthh:Mm:Ss
Safari Browser Audio.Play() Is Not Working
How to Display an Image from an Array of Images in React
How to Set a Header Field on Post a Form
Get the Contents of a Table Row With a Button Click
Angular2 Do Actions After Dom Has Finished Rendering
How to Pass Array Variable from View to Controller in Spring MVC
How to Specify a Single File to Be Seed Only
Customizing Item-Text in V-Select
React Native Flatlist With Clickable Items
Securityerror: Blocked a Frame With Origin from Accessing a Cross-Origin Frame
Validating Array of Different Object Shapes in Yup
Ag-Grid Cellrender With Button Click
How to Pass the Checked and Unchecked Value of Checkboxes in Component.Ts File in Angular
How to Compare Two Json Have the Same Properties Without Order