PokeRwOw PokeRwOw - 1 year ago 73
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 = {{}}

Someone got an idea ? Helper ?

Thanks per advance !


Answer Source

The value of 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 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 at least needs to be in quotes so it's understood as a string value/literal.

var foo = "{{}}";
// 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}}};
// 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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download