1

I would like ejs not to throw an error when rendering a template using a property which does not exist in the object being passed. Is there a way ejs to just display blank value, empty string, null or undefined for the missing property instead of throwing an error and crashing?

let template = 'Name: <%= name %>, Age: <%= age %>';
let result = ejs.render(template, { name: "John" });

Currently I get this error on ejs.render method:

ReferenceError: ejs:1
  >> 1| Name: <%= name %>,Age: <%= age %>
  age is not defined
...
Marko Rochevski
  • 1,184
  • 8
  • 12
  • Possible duplicate of [How would you check for undefined property in ejs for node.js?](https://stackoverflow.com/questions/7289916/how-would-you-check-for-undefined-property-in-ejs-for-node-js) – Cody G Sep 21 '18 at 14:02
  • I know i can use the <%= typeof age!='undefined' ? age : 'undefined' %> syntax, but is there a prettier way to handle this? – Marko Rochevski Sep 21 '18 at 14:03

2 Answers2

0

There are a few ways that you could handle this.

  1. Use nested object properties
    var ejs = require('ejs');
    
    let template = `Name: <%= user.name %> Age: <%= user.age %>`;
    let result = ejs.render(template, { user: { name: "John" }});
    console.log(result)

Result:

Name: John Age:
  1. Better yet, use an if statement to exclude empty props. Here I check if the user.age is a number. You can also use typeof user.age != 'undefined'
var ejs = require('ejs');

let template = `Name: <%= user.name %> <% if(typeof user.age === "number") { %>Age: <%= user.age %><% } %>`;
let result = ejs.render(template, { user: { name: "John" }});
console.log(result)

Result:

Name: John

No matter what, if a variable is undefined, Node will throw an error. Using object properties is a bit more forgiving.

If you're dealing with deeply nested objects that may or may not exist, I might suggest using Lodash get. If your property's parent object is undefined, it will handle the issue. for example if your property is userdata.personalInfo.details.age you can use _.get(userData, ['personalInfo','details','age'], false) - if userData.personalinfo is undefined the function will return false.

drj
  • 533
  • 2
  • 16
-1

With newer javascript you might be able to do something like

var ejs = require('ejs');
var tpl = `
    <% const {foo,bar} = locals %>
    <%=bar%><%=foo%>
  `;
console.log(ejs.render(tpl, { locals: { bar: "baz",} }));
Cody G
  • 8,368
  • 2
  • 35
  • 50