Detect browser language in Rails

后端 未结 5 694
一个人的身影
一个人的身影 2020-12-30 01:04

How do you detect the users language (in RoR) as set in the browser? I will have a select box the user can use at anytime, but I\'d like to default to whatever their browser

5条回答
  •  被撕碎了的回忆
    2020-12-30 01:21

    Last night I did this tiny gem: accept_language

    It can be integrated in a Rails app like that:

    # app/controllers/application_controller.rb
    class ApplicationController < ActionController::Base
      before_action :best_locale_from_request!
    
      def best_locale_from_request!
        I18n.locale = best_locale_from_request
      end
    
      def best_locale_from_request
        return I18n.default_locale unless request.headers.key?('HTTP_ACCEPT_LANGUAGE')
    
        string = request.headers.fetch('HTTP_ACCEPT_LANGUAGE')
        locale = AcceptLanguage.intersection(string, I18n.default_locale, *I18n.available_locales)
    
        # If the server cannot serve any matching language,
        # it can theoretically send back a 406 (Not Acceptable) error code.
        # But, for a better user experience, this is rarely done and more
        # common way is to ignore the Accept-Language header in this case.
        return I18n.default_locale if locale.nil?
    
        locale
      end
    end
    

    I hope it can help.

提交回复
热议问题