RESTful routes js file:
// index route - show all todos
router.get(\"/\", middleware.isLoggedIn,function(req,res) {
Todo.find({ \"author.id\" : req.user._i
Three way to solve the problem...
variant
<script>
var x = "<%= todos %>";
console.log(x);
</script>
variant
<script>
var x = "<%- todos %>";
console.log(x);
</script>
variant [XD]
HTML:
<p id="yy" style="display:none"><%= todos %></p>
Javascript:
<script>
var x = document.getElementById("yy").innerText;
console.log(x);
</script>
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.
http://ejs.co/ says
Can you try using <%- in ejs to read variable value?
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.