Ruby-on-rails 如何在 Slim 模板中访问 CoffeeScript 引擎中的实例变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8108511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access instance variables in CoffeeScript engine inside a Slim template
提问by kapso
I have a Rails controller in which I am setting a instance variable -
我有一个 Rails 控制器,我在其中设置了一个实例变量 -
@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 -
在我的 .slim 模板中,我使用咖啡引擎生成 javascript 并希望从客户端 sie javascript 代码中打印出用户名 -
coffee:
$(document).ready ->
name = "#{@user_name}"
alert name
But this is the javascript that is being generated??
但这是正在生成的javascript??
$(document).ready(function() {
var name;
name = "" + this.my_name;
alert(name);
}
How do I access controller instance variables in my CoffeeScript code??
如何在我的 CoffeeScript 代码中访问控制器实例变量?
I am tagging this as haml since I am guessing haml will have the same issue when using CoffeeScript .
我将其标记为 haml ,因为我猜 haml 在使用 CoffeeScript 时会遇到同样的问题。
回答by Trevor Burnham
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?"
发生的事情是它"#{@user_name}"被解释为 CoffeeScript,而不是被评估并注入到 CoffeeScript 源代码中的 Ruby 代码。您会问:“如何将 Ruby 变量注入到我的 CoffeeScript 源代码中?”
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).
简短的回答是:不要这样做。Rails 团队有意决定在 3.1 中不支持在模板中嵌入 CoffeeScript,因为必须在每个请求上编译 CoffeeScript 会产生显着的性能开销(如果允许将任意字符串注入源代码,则必须这样做) .
My advice is to serve your Ruby variables separately as pure JavaScript, and then reference those variables from your CoffeeScript, e.g.:
我的建议是将您的 Ruby 变量作为纯 JavaScript 单独提供,然后从您的 CoffeeScript 中引用这些变量,例如:
javascript:
user_name = "#{@user_name}";
coffee:
$(document).ready ->
name = user_name
alert name
回答by nathanvda
I tend to avoid inline javascript at all costs.
我倾向于不惜一切代价避免内联 javascript。
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.
在您的 HTML 中存储变量以从您的 javascript 中使用的一种好方法是使用 HTML5 数据属性。这是让您的 javascript 不引人注目的理想选择。

![Ruby-on-rails Rails 中 Thread.current[] 使用的安全性](/res/img/loading.gif)