Accessing Ejs Variable in JavaScript Logic

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



Leave a reply



Submit