Pass variables to JavaScript in ExpressJS

You could use this (client-side): <script> var myVar = <%- JSON.stringify(myVar) %>; </script> You could also get EJS to render a .js file: app.get(‘/test.js’, function(req, res) { res.set(‘Content-Type’, ‘application/javascript’); res.render(‘testPage’, { myVar : … }); }); However, the template file (testPage) would still need to have the .html extension, otherwise EJS won’t find it (unless … Read more

adding .css file to ejs

Your problem is not actually specific to ejs. 2 things to note here style.css is an external css file. So you dont need style tags inside that file. It should only contain the css. In your express app, you have to mention the public directory from which you are serving the static files. Like css/js/image … Read more

Loop through JSON in EJS

JSON.stringify returns a String. So, for example: var data = [ { id: 1, name: “bob” }, { id: 2, name: “john” }, { id: 3, name: “jake” }, ]; JSON.stringify(data) will return the equivalent of: “[{\”id\”:1,\”name\”:\”bob\”},{\”id\”:2,\”name\”:\”john\”},{\”id\”:3,\”name\”:\”jake\”}]” as a String value. So when you have <% for(var i=0; i<JSON.stringify(data).length; i++) {%> what that ends up … Read more

How to create global variables accessible in all views using Express / Node.JS?

After having a chance to study the Express 3 API Reference a bit more I discovered what I was looking for. Specifically the entries for app.locals and then a bit farther down res.locals held the answers I needed. I discovered for myself that the function app.locals takes an object and stores all of its properties … Read more