【发布时间】:2013-10-20 01:07:46
【问题描述】:
我希望我的路线具有 /locale/route 格式而不是 /route?locale=en 等格式。
我在 application_controller.rb 中有以下内容
before_filter :set_locale
def default_url_options(options={})
{ :locale => I18n.locale }
end
private
def set_locale
I18n.locale = (params[:locale] if params[:locale].present?) || cookies[:locale] || 'en'
cookies[:locale] = I18n.locale if cookies[:locale] != I18n.locale.to_s
end
我在 routes.rb 中有这个
scope "/:locale" do
all my routes except for the root
end
对于范围声明之外的根路径,我有以下代码。当我在范围声明中有这些时,它将语言环境设置为 404,但没有找到 404 的语言环境文件。
match '/:locale' => 'landing#index'
root to: 'landing#index'
这是我的标题视图中的代码,人们可以在其中更改语言:
<p class="locale-line"><span class="english-link"><%= link_to_unless_current "#{t :english}", locale: "en" %></span><%= link_to_unless_current "#{t :french}", locale: "fr" %></p>
这里是使用返回根路径的图像的链接的代码:
<%= link_to image_tag("menu-home.jpg", alt: "My Home Page"), root_path %>
<%= link_to image_tag("menu-home.jpg", alt: "My Home Page"), root_url %>
我能够成功获取范围声明中的路由以根据需要显示路由。当一个人最初显示网站并单击页面顶部的任一语言链接时,根路径将显示为 /locale。但是,我的根路径不像我想要的图像标签那样工作。这两个示例都使用 /?locale=en 或 /?locale=fr 显示根路径。
我检查了 guides.rubyonrails.org 和 edgeguides.rubyonrails.org,但没有找到任何示例说明如何为根路径编写 link_to 语句,它将以 /locale 格式显示语言环境。
任何帮助将不胜感激。
【问题讨论】:
-
你在application.rb中有
Rails.application.routes.default_url_options[:locale] = I18n.locale这样的东西吗? -
我认为您可以在范围声明中添加
root to: 'landing#index',在此范围声明之外添加match '/' => "landing#index", locale: 'en'。
标签: ruby-on-rails internationalization routes rails-routing i18n-gem