【发布时间】:2020-02-22 15:29:38
【问题描述】:
我最近开始使用 Rails 和 I18n。
似乎,在我的应用程序中,当我发送 Http 请求以从一个端点移动到另一个端点时,所选的 I18n 参数不是持久的。
即
我被重定向到默认语言 http://localhost:4000/en
我点击一个按钮“Español”来切换语言偏好
页面上的文字是西班牙语
(到目前为止的行为符合预期)
我点击一个按钮进入应用程序的另一个页面,即“视频”
我被重定向到http://localhost:4000/en/video
页面上的文字是英文
可以看出,语言偏好“es”消失了,现在我被重定向回默认的“en”。我的 Rails 版本是 5.1。 这是我的路线.rb
Rails.application.routes.draw do
scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do
root 'pages#home'
get 'accommodation' => 'pages#accommodation'
get 'afterparty' => 'pages#afterparty'
post 'afterparty' => 'pages#create_afterparty'
get 'afterparty/index' => 'pages#afterparty_index'
get 'registry' => 'pages#registry'
get 'rsvp' => 'pages#rsvp'
post 'rsvp' => 'pages#create'
get 'rsvp/index' => 'pages#rsvp_index'
get 'video' => 'pages#video'
end
match '*path', to: redirect("/#{I18n.locale}/%{path}"), :via => [:get, :post]
match '', to: redirect("/#{I18n.locale}"), :via => [:get, :post]
end
这是我的 application_controller.rb:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :set_locale
private
def set_locale
I18n.locale = params[:locale] if params[:locale].present?
end
def default_url_options(options = {})
{locale: I18n.locale}
end
end
这是我在初始化程序目录中定义的 locale.rb:
# Where the I18n library should search for translation files
I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')]
# Permitted locales available for the application
I18n.available_locales = [:en, :es]
# Set default locale to something other than :en
# I18n.default_locale = :es
这是 application.html 的摘录,显示了语言环境参数分配:
<%= t('.language') %>
<%= link_to_unless_current "English", locale: "en" %> |
<%= link_to_unless_current "Español", locale: "es" %>
这里是 application.html 的摘录,它举例说明了将您重定向到不同页面的 2 个锚标记:
<a class="names" href='/'><h4>Christina & Alex</h4></a>
<a class="section" href='/video'>VIDEO</a>
我尝试了几件事都没有成功。请帮助澄清我错在哪里。谢谢。
【问题讨论】:
标签: ruby-on-rails ruby routing rails-i18n