Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing handlebars variable inside client js file

I'm generating a handlebars view with hbs 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}}

Obviously this code throws an error, but what is the preferred way of getting hbs variables inside JavaScript?

Currently I'm running another ajax request to get the same data. but I think it is not wise to make another request for the same data...

like image 273
Dima Grossman Avatar asked Apr 24 '26 23:04

Dima Grossman


1 Answers

Found the solution, seems like i just had to put the handlebars variable inside a string for it to work.

In order to pass and Object to a variable I created hbs helper:

 hbs.registerHelper('json', function(context) {
    return JSON.stringify(context);
 });

and the in my view:

 var currentUser = JSON.parse('{{{json user}}}');

and now i can access the data on the client side js.

like image 87
Dima Grossman Avatar answered Apr 26 '26 12:04

Dima Grossman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!