0

I passed my 'posts' object to HTML this way.

res.render('post', {posts : items });

I can access my object inside HTML using this call, and it will display "John"

<h1><%=posts[0].name%></h1>

However, if I use the same 'posts' object in html but this time put it inside a script for query.

<script>
    var data = <%=posts%>;
    for (var i=0, i<data.length, i++) {
      //My intention is to insert a dynamic html code based on this query   
    {
</script>

My browser always points to <%=posts%> where I assign 'data' variable for the error "Uncaught SyntaxError: Unexpected identifier". It shows arrays of [object, Object], [object, Object].....and posts[i].name does not get print out.

So my question is if I can access it directly on html, why put it inside a tag will result as an error?

Thanks in advance for you help.

RogerMW
  • 95
  • 8

1 Answers1

0

Instead of:

var data = <%=posts%>;

You can use:

var data = <%- JSON.stringify(posts) %>;
rsp
  • 107,747
  • 29
  • 201
  • 177