How to change the locale through URL?

前端 未结 3 1257
攒了一身酷
攒了一身酷 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:14

    Maybe it's better to set locale in routes.rb like this:

    # config/routes.rb
    scope "(:locale)", locale: /en|nl/ do
      resources :books
    end
    

    You can read more here http://guides.rubyonrails.org/i18n.html#setting-the-locale-from-the-url-params

    UPD. If you also save locale to the session, you also need to update it on each request. You can set it in the filter as suggested in the other answer. But I prefer to use less filters:

    def locale_for_request
      locale = params[:locale]
      if locale && I18n.locale_available?(locale)
        session[:locale] = locale
      else
        session[:locale] || I18n.default_locale
      end
    end
    
    # then use it in the around filter: I18n.with_locale(locale_for_request)
    

提交回复
热议问题