Chartjs-Chart.js with handlebar.js shows empty canvas

1👍

You are correct that it will not work if you have String values for your role properties.

This has to do with the fact that you are using Handlebars to produce executable JavaScript.

The code that needs to be updated is:

var role = {{this.role}};
roles.push(role);

This code outputs JavaScript. When the role values are numbers, the output looks like:

var role = 26;
roles.push(role);

The above is perfectly valid JavaScript. However, when role is a String, the output becomes:

var role = analyst;
roles.push(role);

Since there are no quotes around analyst, the JavaScript engine thinks it is an identifier for a variable, but since it cannot find a variable named analyst, it throws a Reference Error.

As we need our role values to be valid JavaScript Strings, we will need to ensure there are quotes around them. The updated template would look like:

var role = "{{this.role}}";
roles.push(role);

Which will produce the following JavaScript:

var role = "analyst";
roles.push(role);

Leave a comment