在客户端js文件中访问handlebars变量 [英] Accessing handlebars variable inside client js file
问题描述
我使用hbs为express js框架生成一个handlebars视图,并且我需要访问从单独的JavaScript文件传递给视图的变量。
例如:
var foo = {{user.name}}
很明显,这段代码会抛出一个错误,但在JavaScript中获取hbs变量的首选方法是什么?
目前我正在运行另一个Ajax请求来获取相同的数据。但我认为再次请求相同的数据是不明智的......
解决方案找到解决方案,看起来像我只需将handlebars变量放在一个字符串中就可以工作。
为了将Object和Object传递给一个变量,我创建了hbs helper:
hbs.registerHelper('json',function(context){
return JSON.stringify(context);
});
以及在我看来:
var currentUser = JSON.parse('{{{json user}}}');
现在我可以访问客户端js上的数据。
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...
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.
这篇关于在客户端js文件中访问handlebars变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!