-1

I'm running a express server and render a list. This is the code of the route:

try {
    let result = await servCollections.prepareDataForListCollections();
    let colls = result.data;
    let messages = result.messages;
    res.render('../views/pages/listcollections', { daten: colls, mess: messages });
} catch (err) {
    console.error(`Error while getting collections `, err.message);
    next(err);
}

In my ejs view I want to pass the mess variable to a javascript function like so:

<main>  

<script>populateMultiMessages( <%= mess %> )</script> 

Then I got the above error, which I can`t understand. Here is the content from mess in a debugger view: debug window of array messages

1
  • JSON.stringify the object and paste it as text so we can see it Commented Mar 24 at 10:42

1 Answer 1

0

The problem is most probably with populateMultiMessages( <%= mess %> ) as EJS does not render your JSON as stringified JSON but internally just uses mess.toString() which will result in populateMultiMessages([object Object],[object Object]) which obviously isn't valid javascript.

To overcome this you could either pass your data already stringified to the renderer

res.render('../views/pages/listcollections', { daten: JSON.stringify(colls), mess: JSON.stringify(messages) })

...

<%- mess %>

or use JSON.stringify in the template

<%- JSON.stringify(mess) %>

Be aware, that if you pass stringified data, of course you cannot iterate the data anymore in the template or access nested data. If you need that, go with the second option.

In both cases be aware, that with <%= ... %> EJS will escape the output to be proper HTML. Ie for instance will replace the double quotes " with &#34;. Thus, you will need to use the raw rendering tag <%- ... %> instead of the encoded <%= ... %> (mind the - vs the =) Also be aware that rendering raw data always bears a certain risk of code injections, so only do that if your input data strems from a trusted source ...

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

1 Comment

<%- JSON.stringify(mess) %> solved the problem, thx

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.