PokeRwOw PokeRwOw - 3 months ago 8
Javascript Question

Accesing handlebars variable via javascript

I'm generating a handlebars view for express js framework, and I need to access the variables I pass to the view from inside a separate JavaScript file.

For example:

var foo = {{user.name}}


Someone got an idea ? Helper ?

Thanks per advance !

PokeRwOw

Answer

The value of user.name needs to be output as a valid JavaScript expression if you want to include it in within a <script>, which will be reevaluating it as code.

Currently, if user.name is "john.doe" for example, the resulting script will be:

var foo = john.doe; // `john` is treated as an object with a `doe` property

The user.name at least needs to be in quotes so it's understood as a string value/literal.

var foo = "{{user.name}}";
// result
var foo = "john.doe";

You can also take advantage of JSON and JavaScript's similarities in syntax, outputting JSON that JavaScript can understand as an Expression, and will already include the quotes.

Handlebars.registerHelper('json', function (content) {
    return JSON.stringify(content);
});
var foo = {{{json user.name}}};
// result
var foo = "john.doe";

Note the triple {{{...}}} in the last example to disable HTML encoding, so you don't end up with:

var foo = &quot;john.doe&quot;