2010-08-25 73 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佈局文件。