Im using the template function for lodash and I want to get lodash to throw an error if the nested object property does not exist but it seems that the function only checks the properties on the initial object that you pass in.
try {
const config = `Hey <%- customer.firstName %> <%- customer.lastName %>, How are you?`;
const res = template(config)({
customer: {
firstName: "Bill",
},
product: {
name: "brush",
price: "$9.99"
}
});
} catch(e) {
console.log(e)
}
The code above returns Hey Bill, How are you?
It does not throw an error when I try to use the last name variable even though it does not exist on customer. Is there anyway to make lodash check nested objects when using the template function?
It shouldn't throw an error, because it is compiling the variable to _.escape(undefined) which returns an empty string.
It should throw an error if you try customer.lastName.anotherProp.
You can explicitly throw an error, if you want, with evaluate delimiters:
try {
const config = `Hey <%- customer.firstName %> <% if (!customer.lastName) { throw 'Object property is not defined!' } else { %><%- customer.lastName %><% } %>, How are you?`;
const res = lodash.template(config)({
customer: {
firstName: "Bill",
},
product: {
name: "brush",
price: "$9.99"
}
});
} catch(e) {
console.log(e)
}