There are a few ways that you could handle this.
- 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:
- 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
.