Rumba
Rumba

Reputation: 181

Accessing passed EJS variable in Javascript file

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.

Upvotes: 11

Views: 27278

Answers (5)

enhancedJack
enhancedJack

Reputation: 275

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.

Upvotes: 4

Mario Mazzola
Mario Mazzola

Reputation: 41

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.

Upvotes: 1

Mohimenul Joaa
Mohimenul Joaa

Reputation: 686

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>
    

Upvotes: 28

TheRedstoneTaco
TheRedstoneTaco

Reputation: 311

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();

Upvotes: 15

Chetan acharekar
Chetan acharekar

Reputation: 91

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?

Upvotes: 1

Related Questions