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

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more