nasoj1100 nasoj1100 - 28 days ago 7
Node.js Question

How can I access ejs variables in an external script

When I pass a variable to my html page with NodeJS I can access it with an inline script as follows:

// passing myVar from the server
router.get('/', (req, res) => {
res.render('index', { myVar: 'test'});

// access in index.ejs
let myVar = <%- JSON.stringify(myVar) %>;

If I try to use an external script here instead of the inline I encounter an error over using the ejs syntax
<%- %>
. How can I access myVar in an external script?


Code between <%- and %> is server side code.

If you move it out of your EJS template file and into a static JS file, then you can't get at the data. It won't be replaced and you'll send the EJS template to the browser instead of processing it on the server to generate a document.

If you move it out of the EJS template file that generates HTML and into a different EJS template file that generates JavaScript then it will work as normal (except that it will have a different URL with a different end point in your server side code, so you will need to move the server side code which populates the variables you are trying to access).

You have two reasonable options:

Have two script elements.

One to get the data for the page:

<script>let myVar = <%- JSON.stringify(myVar) %>;</script>

And one to contain the JavaScript logic:

<script src="/js/logic.js"></script>

Move the generated data into the page

<div data-myVar="<%- JSON.stringify(myVar).replace(/"/g, "&quot;"); %>">...</div>

… and then access it through the DOM.