如何在 Slim 模板内访问 CoffeeScript 引擎中的实例变量
我有一个 Rails 控制器,在其中设置一个实例变量 -
@user_name = "Some Username"
在我的 .slim 模板中,我使用咖啡引擎生成 javascript,并希望从 client-sie javascript 代码打印出用户名 -
coffee:
$(document).ready ->
name = "#{@user_name}"
alert name
但这是正在使用的 javascript生成??
$(document).ready(function() {
var name;
name = "" + this.my_name;
alert(name);
}
如何访问 CoffeeScript 代码中的控制器实例变量?
我将其标记为 haml 因为我猜测 haml 在使用 CoffeeScript 时也会遇到相同的问题。
I have a Rails controller in which I am setting a instance variable -
@user_name = "Some Username"
In my .slim template I am using coffee engine to generate javascript and want to print out the user name from client-sie javascript code -
coffee:
$(document).ready ->
name = "#{@user_name}"
alert name
But this is the javascript that is being generated??
$(document).ready(function() {
var name;
name = "" + this.my_name;
alert(name);
}
How do I access controller instance variables in my CoffeeScript code??
I am tagging this as haml since I am guessing haml will have the same issue when using CoffeeScript .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
发生的情况是
"#{@user_name}"
被解释为 CoffeeScript,而不是被评估并注入到 CoffeeScript 源中的 Ruby 代码。您会问:“如何将 Ruby 变量注入到我的 CoffeeScript 源中?”简短的回答是:不要这样做。 Rails 团队故意决定不支持 3.1 中模板中嵌入的 CoffeeScript,因为必须针对每个请求编译 CoffeeScript 会带来巨大的性能开销(如果您允许将任意字符串注入到源代码中,您就必须这样做) 。
我的建议是将 Ruby 变量作为纯 JavaScript 单独提供,然后从 CoffeeScript 中引用这些变量,例如:
What's happening is that
"#{@user_name}"
is being interpreted as CoffeeScript, not as Ruby code that's evaluated and injected into the CoffeeScript source. You're asking, "How do I inject a Ruby variable into my CoffeeScript source?"The short answer is: Don't do this. The Rails team made an intentional decision not to support embedded CoffeeScript in templates in 3.1, because there's significant performance overhead to having to compile CoffeeScript on every request (as you'd have to do if you allowed arbitrary strings to be injected into the source).
My advice is to serve your Ruby variables separately as pure JavaScript, and then reference those variables from your CoffeeScript, e.g.:
我倾向于不惜一切代价避免内联 JavaScript。
在 HTML 中存储变量并在 javascript 中使用的一个好方法是使用 HTML5 数据属性。这是保持 JavaScript 不引人注目的理想选择。
I tend to avoid inline javascript at all costs.
A nice way to store variables in your HTML, to be used from your javascript, is to use the HTML5 data-attributes. This is ideal to keep your javascript unobtrusive.
您还可以使用:
这是因为 JSON 是 JavaScript 的子集。
You could also use:
This is because JSON is a subset of JavaScript.