How to change the locale through URL?

前端 未结 3 1258
攒了一身酷
攒了一身酷 2020-12-06 19:33

In my bi-lingual Rails 4 application I have a LocalesController like this:

class LocalesController < ApplicationController

  def change_loca         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-06 20:03

    This is how I did it in one of Rails 4 applications:

    in config/routes.rb:

    Rails.application.routes.draw do
      scope "(:locale)", locale: /#{I18n.available_locales.join("|")}/ do
        # rest of your routes here
        # for example:
        resources :projects
      end
    end
    

    make sure in config/environments/production.rb this line is uncommented:

    config.i18n.fallbacks = true
    

    If you wish to have a default_locale setup other than :en, then in config/application.rb, uncomment this line:

    config.i18n.default_locale = :de # and then :de will be used as default locale
    

    Now, last part of your setup, add this method in ApplicationController:

    class ApplicationController < ActionController::Base
      # Prevent CSRF attacks by raising an exception.
      # For APIs, you may want to use :null_session instead.
      protect_from_forgery with: :exception
    
      before_action :set_locale
    
      private
        def set_locale
          I18n.locale = params[:locale] || session[:locale] || I18n.default_locale
          session[:locale] = I18n.locale
        end
    
       def default_url_options(options={})
         logger.debug "default_url_options is passed options: #{options.inspect}\n"
         { locale: I18n.locale }
       end
    end
    

    Now, your application can be accessed as: http://localhost:3000/en/projects, http://localhost:3000/fr/projects, or http://localhost:3000/projects. The last one http://localhost:3000/projects will use :en as its default locale(unless you make that change in application.rb).

提交回复
热议问题