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

Can I use conditional statements with EJS templates (in JMVC)?

Conditionals work if they’re structured correctly, I ran into this issue and figured it out. For conditionals, the tag before else has to be paired with the end tag of the previous if otherwise the statements will evaluate separately and produce an error. ERROR! <% if(true){ %> <h1>foo</h1> <% } %> <% else{ %> <h1>bar</h1> … Read more

How to escape HTML in node.js EJS view?

You are escaping the value correctly by using: <%= bloglist[i].Text %> If you want to allow HTML to be rendered, then you want an “unescaped” value. To do that use the following: <%- bloglist[i].Text %> All I did was replace the equal (=) with a dash (-). Reference: https://github.com/visionmedia/ejs/tree/0.8.3#features

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

Passing an object to client in node/express + ejs?

In Node.js: res.render(‘mytemplate’, {data: myobject}); In EJS: <script type=”text/javascript”> var rows =<%-JSON.stringify(data)%> </script> SECURITY NOTE : Don’t use this to render an object with user-supplied data. It would be possible for someone like Little Bobby Tables to include a substring that breaks the JSON string and starts an executable tag or somesuch. For instance, in … Read more

Node.js – EJS – including a partial

With Express 3.0: <%- include myview.ejs %> the path is relative from the caller who includes the file, not from the views directory set with app.set(“views”, “path/to/views”). EJS v1 includes EJS v2 includes (Update: the newest syntax for ejs v3.0.1 is <%- include(‘myview.ejs’) %>)