Search code examples
javascriptnode.jsexpressnunjucks

Node JS Template Add Object To Window


I was wondering if there was a way, when rendering a javascript template with Node, to attach an object or values to the window object. For example, if I wanted to take the data that was passed to the res.render function and attach it to the window object for later use. Later use would be for hash routing. Currently I am using Nunjucks.

res.render('index', {data:{name:'Max'}});
// How could  I attach data to the window object for later use.

Any other suggestions would be appreciated.

EDIT: I didn't make this clear, but when I was referring the the window object, I was referring to the client window object. Not a window object in Node. When rendering the template how can I add items to the window object.


Solution

  • You can render an inline script right to the html output:

    <body>
    <script>
    window.data = {name: 'Max'};
    </script>
    </body>
    

    But adding properties to global object is not recommended, better use a namespace like:

    var app = {};
    app.data = {name: 'Max'};