How to include external .js file to ejs Node template page

You can’t.

Note: You can only pass data from .ejs file to .js file but not the other way. It won’t work because .ejs is rendered on the server side while .js runs on the client side.
I am assuming you are using EJS on server side

1) You can pass an ejs variable value to a Javascript variable

    <% var test = 101; %> // variable created by ejs
    <script>
       var getTest = <%= test  %>;  //var test is now assigned to getTest which will only work on browsers
       console.log(getTest);  // successfully prints 101 on browser
    </script>

2) You can’t pass a js variable value to a ejs variable

Yes, you can’t: if it is on server.

Why:

The EJS template will be rendered on the server before the js is started execution(it will start on browser), so there is no way going back to server and ask for some previous changes on the page which is already sent to the browser.

Leave a Comment