javascriptexpressejsfunction-call

Node / express / ejs / Uncaught SyntaxError: missing ] after element list


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


Solution

  • 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 ...