DEV Community

Željko Šević
Željko Šević

Posted on • Originally published at sevic.dev on

Identifying missing variables in Handlebars templates

Handlebars is a template engine that can create server-side views, e-mail templates, and invoice templates by injecting JSON data into HTML.

Resolving all variables in a Handlebars template is essential to maintain the accuracy of the displayed information and to prevent incomplete content or layout problems.

The following snippet checks for missing variables by overriding the default nameLookup function. It logs a warning for unresolved variables and sets the default value, empty string, in this case.

// ...
const originalNameLookup = Handlebars.JavaScriptCompiler.prototype.nameLookup;
Handlebars.JavaScriptCompiler.prototype.nameLookup = function(
  parent,
  name,
  type
) {
  if (type === 'context') {
    const messageLog = JSON.stringify({
      message: `Variable is not resolved in the template: ${name}`,
      level: WARNING_LEVEL
      // ...
    });
    return `${parent} && ${parent}.${name} ? ${parent}.${name} : (console.log(${messageLog}), ''`;
  }

  return originalNameLookup.call(this, parent, name, type);
};
// ...
const result = Handlebars.compile(template)(data);
Enter fullscreen mode Exit fullscreen mode

Course

Build your SaaS in 2 weeks - Start Now

Top comments (0)