Ember: dynamic switch to chosen language (using i18n library)

前端 未结 3 1273
孤独总比滥情好
孤独总比滥情好 2021-02-05 16:05

I am using the ember-i18n library for translation of static strings used throughout my application. As the language files are rather big, I do not want to load at application st

3条回答
  •  无人及你
    2021-02-05 16:26

    I tried all the ways listed here and had various issues with all of them. I found a much more elegant hack to make this work.

    CAVEAT: This only works if you are serving Ember using Rails (but could probably be adapted to work with any server-side framework).

    In Rails, the i18n-js gem integrates with Rails default locales. Dynamic switching in Ember is a huge pain because you must manually redraw all views or reset the app to get the language to update when I18n.locale is changed.

    The best way I have found to do it is to specify locale using parameters set on Rails, before Ember even loads.

    RAILS configuration:

    Make your ember#index controller action look like this:

    def index
      if params[:locale]
        I18n.locale = params[:locale]
      end
    end
    

    Then in your html template, add this single line of javascript:

    
      
        <%= stylesheet_link_tag :application, :media => :all %>
        <%= stylesheet_link_tag    "application", 'http://fonts.googleapis.com/css?family=Roboto:400,300,300italic,100,700' %>
        <%= stylesheet_link_tag    "application", 'http://fonts.googleapis.com/css?family=Roboto+Condensed:400,300,300italic' %>
        <%= javascript_include_tag :application %>
        Review Blaster 9000
    
    
        
    
    
      
      
    
    
          <%= yield %>
    
    
      
    
    

    Then in your template, specify the language switchers like this:

    English
    Spanish
    ...etc...
    

    Clicking on those links will result in a complete refresh of the app. Rails will parse the parameter, set I18n and then Ember will start with the correct value already set beforehand, so everything will draw correctly.

提交回复
热议问题