vardha
vardha

Reputation: 414

EJS access express variable in JS onload function

I know you can get the value of variables in an ejs file like so,

<h1><%= title %></h1>

if i were to use the same title variable in a onload javascript function in the same ejs page, how would i use it . for instance

<script>
window.onload(){
var s = <%= title %>
alert(s);
}
</script>

this function produces a console error saying

Uncaught syntax error: Unexpected identifier

although I'm able to see the actual value of the variable

Upvotes: 3

Views: 3251

Answers (3)

Kira
Kira

Reputation: 118

When you have

var s = <%= title %>

This parses it like it would for HTML, so there are no quotes. For example, if the title was "My Page", your javascript would be:

var s = My Page

Since there are no quotes around My Page, this gives a JavaScript error. You could use JSON.parse, or just put quotes around it to fix this:

var s = "<%= title %>"

Upvotes: 0

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123473

To output it within a script, the result will need to be understood as code.

Since you didn't note the value of title, I'll assume for the examples:

res.render('view', { title: 'My Site' });

When you use var s = <%= title %>, this results in creating the statement as:

var s = My Site

In this, My and Site are interpreted as individual variables separated only by an unexpected space. The engine is confused when it reaches Site without an operator between them, thus the Unexpected identifier you're getting.


It needs to instead create the statement:

var s = "My Site"

So the client script can also understand it as a string value.

One trick to accomplishing this is using JSON.stringify(). Since JSON took its syntax from JavaScript's expressions and literals, a JavaScript engine is capable of making sense of the result in many contexts (though, with its own take on strings, objects, etc.):

var s = <%- JSON.stringify(title) %>

Note, though, the switch to using <%- %> vs. <%= %>. This will disable HTML encoding, which is unnecessary and can lead to odd results inside of a <script>.

Upvotes: 4

Nguyen Sy Thanh Son
Nguyen Sy Thanh Son

Reputation: 5376

I think you should try: html:

<h1 id="title"><%= title %></h1>

Js:

  <script>
    window.onload(){
    var s = document.getElementById("title").innerText;
    alert(s);
    }
  </script>

Upvotes: 0

Related Questions