代码之家  ›  专栏  ›  技术社区  ›  StefanS

使YML翻译在JavaScript文件中可用

  •  3
  • StefanS  · 技术社区  · 16 年前

    我在当前的Rails项目中使用jquery,我想有一些方法来使用JavaScript中YML文件的翻译。

    我知道我可以在.js.erb模板中轻松地使用它们。但是/public/javascript中的javascript文件呢?

    看起来像巴比鲁( http://github.com/toretore/babilu )会做我想做的。我只是想知道是否还有其他插件…不是我对巴比鲁有什么不满,而是我喜欢有选择;-)

    另外,在Rails 2.3.5中可能有一些默认的方法。我不知道,我可能根本不需要使用插件?

    1 回复  |  直到 15 年前
        1
  •  5
  •   sandstrom    15 年前

    控制器:

    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层中使用的子集(不应该太多)。