【问题标题】:Rails - redirection with localeRails - 使用语言环境重定向
【发布时间】:2017-03-17 17:12:10
【问题描述】:

我在application.rb 中设置了locale 的基本选项:

config.i18n.available_locales = [:pl, :en]
config.i18n.default_locale = :pl

并且还限定了路线:

Rails.application.routes.draw do
    get '/:locale', to: 'home#index'
    root            to: 'home#index'

    scope ":locale", locale: /#{I18n.available_locales.join("|")}/  do
      get 'settings', to: 'home#settings'
    end
end

这样我可以访问我在www.mysite.comwww.mysite.com/en or pl 下的根站点,以及在url 中包含语言环境时我的设置站点。

现在假设用户输入了www.mysite.com/settings。我想让我的应用知道 url 中没有语言环境,所以去抓取default_locale,设置它,然后重定向到www.mysite.com/pl/settings

我该怎么做?

PS 我也将这些添加到我的ApplicationController

before_action :set_locale

    def set_locale
      I18n.locale = params[:locale] || I18n.default_locale
    end

    def default_url_options
      { locale: I18n.locale }
    end

【问题讨论】:

    标签: ruby-on-rails redirect rails-i18n


    【解决方案1】:

    如果用户在接受语言标头中没有波兰语,即使您将其他非本地化路由重定向到波兰语,最好将 根路径 重定向到英语。

     # Usefull to parse accept-language header but also for browser detection
     gem 'browser'
    

    在 routes.rb 中:

    Rails.application.routes.draw do
      scope ':locale', locale: /#{I18n.available_locales.join('|')}/ do
        # Your routes...
    
        # Home
        root 'pages#index'
      end
    
      root 'pages#detect_locale'
    
      # Catch all requests without a available locale and redirect to the PL default...
      # The constraint is made to not redirect a 404 of an existing locale on itself
      get '*path', to: redirect("/#{I18n.default_locale}/%{path}"), 
                   constraints: { path: %r{(?!(#{I18n.available_locales.join('|')})\/).*} }
    end
    

    在控制器中:

    class PagesController < ApplicationController
      def index; end
    
      # Detect localization preferences
      def detect_locale
        # You can parse yourself the accept-language header if you don't use the browser gem
        languages = browser.accept_language.map(&:code)
    
        # Select the first language available, fallback to english
        locale = languages.find { |l| I18n.available_locales.include?(l.to_sym) } || :en
    
        redirect_to root_path(locale: locale)
      end
    end
    

    【讨论】:

    • 我想知道这个答案中提出的解决方案是否可以处理 activestorage 图像路径未重定向到语言环境路径并得到 404 的情况?
    【解决方案2】:
    Rails.application.routes.draw do
      scope ':locale', locale: /#{I18n.available_locales.join("|")}/ do
        root 'users/landing#index'
        get '*path', to: 'users/errors#not_found'
      end
      root to: redirect("/#{I18n.default_locale}", status: 302), as: :redirected_root
      get "/*path", to: redirect("/#{I18n.default_locale}/%{path}", status: 302)
    end
    

    【讨论】:

    • 你应该解释你的代码为什么它回答了这个问题。这样,它为 OP 提供了更多帮助。 :)
    • 从 -1 上升到 0 因为部分答案实际上给出了我所需要的,即使没有解释
    猜你喜欢
    • 1970-01-01
    • 2018-09-10
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2013-12-01
    • 1970-01-01
    相关资源
    最近更新 更多