3

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

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

@vardha: This should be the accepted answer. Nicely explained and to the point.
0

I think you should try: html:

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

Js:

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

2 Comments

I added ";" in line number three
This is what i tried but was wondering if this is the right approach(assign it to a html tag (style=hidden) and then getting the value during onload
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.