0

I am using Nodejs with ejs template. I have an array in my Nodejs backend that looks like this:

array= [false,false,false,false]

Now, if I try to send this to my ejs doing something like

res.render("home",{myarray:array}

and in my ejs(frontend)

let myarray = <%- myarray %>

I get:

Uncaught SyntaxError: Unexpected token false

which upon inspection shows

let myarray = false,false,false,false

However, in my backend if I change

res.render("home",{myarray:array}

to

res.render("home",{myarray:JSON.stringify(array)}

Everything works fine. Myarray now becomes an array again:

[false,false,false,false]

I just do not understand why JSON.stringify helps me send an array from the backend to the front end when I cannot send a regular array.

1

2 Answers 2

1

You can use direct array in your ejs but you will have to use the loop in ejs. If you are sending via JSON.stringify you can revert via JSON.parse();

Sign up to request clarification or add additional context in comments.

Comments

0

In general, when frontend read anything from the server everything is in document/string format and needs to be deciphered.

Since ejs will pass variables in html format, all variables will need to be stringified.

Instead of passing the stringified variable directly, You can stringify your variables in Scriptlet as well. let myarray = <%- JSON.stringify(myarray) %>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.