2010-08-25 110 views
0

我想设置一个全局常量(在Rails),然后根据我想要在JavaScript文件(它包含在我的应用程序的每个页面中)中添加一个条件。我也有一些基于这个变量的Rails依赖代码。基于Rails变量的Javascript条件

这样做的最好方法是什么?

回答

2

在application_controller.rb

def before_filter 
    # This variable will be available in all controller actions and views 
    @my_global = "testing" 
end 

在application.html.erb

<script type="text/javascript"> 
    var my_global = "<%= @my_global %>" 
</script> 
+0

这看起来像是最好的方法...(我没有尝试宝石方式) 谢谢! – Garfield 2010-08-31 06:20:24

1

您可以定义一个全局变量,如:window.profileName = 'Shikher';。或者,如果你需要几个全局变量,我建议建立一个范围:

var Globals = {}; 
Globals.profileName = '<%= @user.profile_name %>'; 

和其他地方

Globals.userId = '<%= @user.id %>'; 

在情况下,你会用它无处不在,你可以插入全局在右侧defenition布局文件。