Is it possible to access the whole object, which is passed into PUG, inside of an inline script without converting it with !{JSON.stringify(object)};
// renderController.js res.render('../events', { events: {[ {...}, {...}, ... ]}, });
Using !{JSON.stringify(events)};
converts existing date-objects to strings, which than needs to be converted back.
Wanted behavior:
// events.pug script. console.log(events[0].date.toLocaleString());
Advertisement
Answer
Is it possible to access the whole object, wich is passed into PUG, inside of an inline script without converting it?
No, it is not. Your inline script runs in the browser. The object you passed to the Pug script existed only on the server and is long gone and was never available in the browser.
So, as you seem to already know, the only way to share data like that from the server to an inline script that runs in the browser is to put the data into a Javascript variable in the page itself and the easiest way to do that is to “render” it to JSON in some variable definition inside a script in the page. That will then establish a variable within the inline script that contains the desired data.
Note, that the data must be serializable to JSON for this to work. Some things such as server-side socket objects cannot be transferred to the front-end in this way because they contain references to native objects which can’t be converted to JSON and wouldn’t be useful on a different computer anyway.