Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJs and Ejs Pass Arrays to page

I am trying to pass an array to an .ejs page, however when I try use

var test ="<%= data %>";
console.log(test);

I get the output

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object

Console.log on the nodejs file works fine, but its when I try console.log client side it messes up.

like image 723
h00j Avatar asked May 12 '13 16:05

h00j


People also ask

How do I navigate to another page in EJS?

As illustrated in the image above, the best way to navigate different web pages using ejs template is to ensure you create a folder called "partials" in your project's "views folder directory" where you have your other ejs files. 1) Then in that "partials folder" create 2 separate ejs files called header. ejs & footer.


1 Answers

The issue is likely with <%= data %>, rather than console.log(). If you check the result client-side, you'll probably see:

var test ="[object Object],[object Object],[object Object],...";

When you simply print an Array, this will just .join() the elements, calling .toString() on each. And:

new Object().toString() === "[object Object]"

To output the data so it can be consumed, you can use JSON.stringify():

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

This takes advantage of JSON's syntax being based on JavaScript's synax to output an Array literal of Object literals:

var test = [{"prop":"value"},...];
like image 83
Jonathan Lonowski Avatar answered Nov 15 '22 23:11

Jonathan Lonowski