2010-01-31 80 views
3

我在當前的Rails項目中使用jQuery,我想用一些方法在Javascript中使用我的yml文件中的翻譯。在Javascript文件中提供yml翻譯

我知道我可以在我的.js.erb模板中輕鬆使用它們。但是/ public/javascript中的JavaScript文件呢?

它看起來像Babilu(http://github.com/toretore/babilu)會做我想要的。我只是想知道是否有其他的插件...這不是我有反對Babilu,但我喜歡有選擇;-)

也可能是在Rails 2.3中有一些默認的方式0.5。我不知道,我可能根本不需要使用插件?

回答

5

控制器:

class JavascriptsController < ApplicationController 

    skip_before_filter :authorize 
    respond_to :js 
    layout false 
    caches_page :locale # don't know if this is reset on server restart. 

    def locale 

    # http://edgeguides.rubyonrails.org/caching_with_rails.html 
    @translations = I18n.translate('javascripts') 

    end 

end 

視圖腳本:

Translations = <%= raw @translations.to_json %>; 

和application.html.haml:

= javascript_include_tag "locale.js?language=#{I18n.locale}" # JavascriptsController 

然後添加一些簡單的JS中查找鍵在哈希。相當容易修復。另外,這樣你不會將所有的翻譯都傳遞給js,只是在javascript層實際使用的子集(不應該太多)。