如何在Slim模板中访问CoffeeScript引擎中的实例变量 [英] How to access instance variables in CoffeeScript engine inside a Slim template

查看:118
本文介绍了如何在Slim模板中访问CoffeeScript引擎中的实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails控制器,其中设置一个实例变量 -

I have a Rails controller in which I am setting a instance variable -

@user_name = "Some Username"

在我的.slim模板中,我使用咖啡引擎生成javascript并想从客户端打印出用户名-sie javascript代码 -

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

是正在生成的javascript

But this is the javascript that is being generated??

$(document).ready(function() {
    var name;
    name = "" + this.my_name;
    alert(name);
}

如何在我的CoffeeScript代码中访问控制器实例变量

我将此标记为haml

I am tagging this as haml since I am guessing haml will have the same issue when using CoffeeScript .

推荐答案

发生的是#{ @user_name}被解释为CoffeeScript,而不是被评估并注入到CoffeeScript源代码中的Ruby代码。你问的是如何将Ruby变量注入到我的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?"

简短的答案是:不要这样做。Rails团队有意决定不在3.1中的模板中支持嵌入式CoffeeScript,因为有显着的性能开销,在每个请求上编译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).

我的建议是单独提供你的Ruby变量作为纯JavaScript,然后从您的CoffeeScript中引用这些变量,例如:

My advice is to serve your Ruby variables separately as pure JavaScript, and then reference those variables from your CoffeeScript, e.g.:

javascript:
  user_name = "#{@user_name}";
coffee:
  $(document).ready ->
    name = user_name
    alert name

这篇关于如何在Slim模板中访问CoffeeScript引擎中的实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆