【问题标题】:Rails root path with locale but without query string带有语言环境但没有查询字符串的 Rails 根路径
【发布时间】:2017-07-06 10:50:45
【问题描述】:

我想将 i18n 应用到我的应用程序的根路径。 Rails i18n guides 建议:

当然,您需要特别注意应用程序的根 URL(通常是“主页”或“仪表板”)。像 http://localhost:3001/nl 这样的 URL 不会自动工作,因为您的 routes.rb 中的根 to: "books#index" 声明没有考虑语言环境。 (这是正确的:只有一个“根”URL。)

您可能需要像这样映射 URL:

# config/routes.rb
get "/:locale" => "dashboard#index"

但是,当使用 URL 帮助程序时,此配置不能很好地工作。下面生成一个带有查询字符串的 URL:

root_path(locale: "fr") # => "/?locale=fr"

但我想在路径中生成一个带有语言环境的 URL:

/fr

【问题讨论】:

    标签: ruby-on-rails rails-i18n


    【解决方案1】:

    通过定义rootlocale_root

    # config/routes.rb
    root to: "dashboard#index"
    
    scope "/:locale" do
      get "/", to: "dashboard#index", as: :locale_root
    end
    

    然后您可以使用 locale_root_pathlocale_root_url 助手:

    locale_root_path(locale: "fr") # => "/fr"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 2021-09-08
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多