0

In my Express JS app, I am using ejs view engine, I want to pass variable to javascript file on client side.

This is my render:

return res.render('data/show', {
    data: data
});

This is working for me:

<script>
    var data = <%- JSON.stringify(data) %>;
    console.log(data);
</script>

But my function is in separate .js file that I am including, when I am using the same code:

function gettingData() {
    var data = <%- JSON.stringify(data) %>;
    console.log(data);
}

I am getting syntax error:

Uncaught SyntaxError: Unexpected token <

Thank you in advance for any suggestions.

2 Answers 2

1

I haven't worked with EJS, but my guess would be that:

<%- JSON.stringify(data) %>

...only works as a substitution in the HTML files being served up by the node server (with an .ejs extension, I believe), but that the above would come straight through as-is in a separate .js file being loaded separately.

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

1 Comment

<%- JSON.stringify(data) %> works only in .html file. I am looking for way to access this 'data' in .js file that is included.
0

You could give this a shot...JSON.stringify(<%= data %>). Hope this helps :)

7 Comments

unfortunately your code is giving me the same syntax error. It seems that <%%> ejs marks are not recognized inside .js file.
Put the whole thing in quotes. var someVar = "<%= JSON.stringify(data) %>"
I was trying this also. Result is that someVar is type of String and equal "<%= JSON.stringify(data) %>". This was't even executed, javascript is treating it's as regular string.
It worked for me...but just realized that it was because I was using it within the script tags in the .ejs file.
Yes, exactly, with <script> tag everything is workin fine, but my script is getting big, that's why it's necessary to include another file and not write everything inside .html.
|

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.