How can I pass an array to an ejs template in express?

ejs, express, javascript, node.js

Solution

In EJS echoing something is done with

<%= %>

or

<%- %>

In the last example you're not echoing anything, so nothing is passed to `data` and it's undefined.

In the first example you're also escaping the echoed content, so try using echoing the string unescaped as that will remove the entities.

var data = <%- JSON.stringify(room_info) %>

Problem

I'm trying to pass an array which contains objects to views of ejs in express, but it doesn't work. In server, ``` var roominfo = function(roomname){ this.roomname=roomname; }; room_info_array= new Array(1); room_info_array[0]=new roominfo("room"); app.get("/", function(req, res){ res.render('login',{room_info:room_info_array}); }); ``` In client, ``` <script type="text/javascript"> var data = <%= JSON.stringify(room_info) %> </script> ``` this shows error "Uncaught SyntaxError: Unexpected token & ". ``` var data = [{&quot;roomname&quot;:&quot;room&quot;}]" ``` I tried this ``` <script type="text/javascript"> var data = <% JSON.stringify(room_info) %> </script> ``` However this shows data is undefined. How should I pass the array to ejs correctly?

Original source