Accessing passed EJS variable in Javascript file

Viewed 24684

RESTful routes js file:

// index route - show all todos
router.get("/", middleware.isLoggedIn,function(req,res) {
  Todo.find({ "author.id" : req.user._id}, function(err, allTodos) {
    if(err) {
      console.log(err);
    } else {
      res.render("todo/index", {todos: allTodos});
    }
  });        
});

My index.ejs file has:

<script src="/scripts/todoCalendar.js"></script>

at the end of the body tag and I want to access the passed variable todos inside my todoCalendar.js file. I tried putting

<script>
  var x= <%= todos %>
</script>

but it says x is undefined when i try to do a console.log(x) inside my todoCalendar.js file.

Any help is greatly appreciated.

5 Answers

Three way to solve the problem...

  1. variant

    <script>
        var x = "<%= todos %>";
        console.log(x); 
    </script>
    
  2. variant

    <script>
        var x = "<%- todos %>";
        console.log(x); 
    </script>
    
  3. variant [XD]

    HTML:

    <p id="yy" style="display:none"><%= todos %></p>
    

    Javascript:

    <script>
        var x = document.getElementById("yy").innerText;
        console.log(x); 
    </script>
    

By formatting the html printing of the JSON you get from the server and using javascript (my case jQuery) to retrieve that text, store it, and remove it from the html :)

EJS:

<span id='variableJSON' hidden>
    <%= JSON.stringify(passedInEjsVariable); %>
</span>

JavaScript:

var variableJSON = JSON.parse($('#variableJSON').text());
$('#variableJSON').remove();

Only this works in my case. All versions with "" or with <%= fail.

<script>
  var todos = <%-JSON.stringify(todos)%>;
  for (var item of todos) {
    console.log(item)
  }
</script>

Thing to note: if using VS Code with formatting on save for .ejs files, <%- gets split into <% - and you get Uncaught SyntaxError: Unexpected token ';' and what worked a second ago, suddenly stops working.

http://ejs.co/ says

  1. <% 'Scriptlet' tag, for control-flow, no output
  2. <%= Outputs the value into the template (HTML escaped)
  3. <%- Outputs the unescaped value into the template
  4. <%# Comment tag, no execution, no output

Can you try using <%- in ejs to read variable value?

I am afraid you can't use EJS tags inside a file with a .js extension.

If you put the js code at the bottom of the EJS document, there is no problem.

In the backend you do:

res.render('todo/index', {todos: JSON.stringify(alltodos)}); 

In your ejs file you do:

<script>
 var x= <%- todos %>;
 console.log(x);
</script>

This works fine. I ve just tested for my project.

If you want to use the same code inside a separate file with .js extension, it will not work. You get an 'unexpected token <' error in the browser console.

The only option you have is to print todos into a hidden DIV inside the ejs file and then get in through javascript (you can use innerText or innerHTML) and store it inside a variable. A bit hacky but it does the trick.

Related