我正在尝试在我的rails应用程序上实现国际化。这是我的应用程序控制器的一部分
before_action :set_locale
def set_locale
I18n.locale = extract_locale_from_tld || I18n.default_locale
end
def extract_locale_from_tld
parsed_locale = request.host.split('.').last
I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
end
似乎没有用,我只能设置url params的语言环境,让我在我不想要的路线中使用scope "(:locale)", locale: /en|se/ do
。
从导轨指南中,他们指出应该像这样实现切换菜单。
link_to("Deutsch", "#{APP_CONFIG[:deutsch_website_url]}#{request.env['REQUEST_URI']}")
你是如何实现这个的? 我目前的切换菜单看起来像这样。
<% if I18n.locale == I18n.default_locale %>
<li><%= link_to image_tag("eng.png", :alt => "England", :class =>"round"), :locale=>'en' %>
<li><h5><%= link_to_unless I18n.locale == :se, "Swedish", "#{'http://www.natkurser.se'}" %></h5>
<% else %>
<li><%= link_to image_tag("swe.png", :alt => "Sweden", :class =>"round"), :locale=>'se' %>
<li><h5><%= link_to_unless I18n.locale == :en, "English", "#{'http://gettheskill.com'}" %></h5>
<%end%>
我已经将127.0.0.1 gettheskill.com和127.0.0.1 natkuser.se添加到/ etc / hosts,但它仍然不能用于开发。我修改了哪些文件以便它可以在生产中使用?我在想nginx配置文件。最终,路线应该如何出现。这是rails国际化文档中似乎遗漏的主要内容。详细的答案将不胜感激。
答案 0 :(得分:1)
你的问题不是很有条理,我会尽量给出一些提示。
如果您想查看区域设置和域的工作示例,请查看the onruby project。它是一个多租户应用程序,每个租户都可以配置自己的域和默认语言环境。
这是实施方式:
该网站使用Cookie来跟踪当前所选的区域设置。
如果未设置cookie,则使用域名来解析它。要在开发中测试,您必须使用/etc/hosts
并在其中添加域,以便可以在本地解析它们。在你的情况下,这将是gettheskill.com:3000访问你的应用程序。
我通常使用稍微不同的域名,要么添加子域名,要么添加不同的域名,这样我仍然可以通过互联网访问域名而无需编辑/etc/hosts
。
语言切换只需将参数locale=XY
附加到链接即可。所以params[:locale]
始终优先,并切换选定的区域设置并为cookie设置新值。
我希望这是足够的信息,让它为你工作。
和NO,没有必要在rails或/etc/hosts
文件之外配置。
答案 1 :(得分:1)
我已按照导轨指南进行了相应的i18n设置。我无法理解你的问题。我唯一不同的是提取语言环境。我使用request.subdomains.first而不是最后一个。
def extract_locale_from_subdomain
parsed_locale = request.subdomains.first
I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
end
您是否按照rails指南中的说明设置了加载路径。
# in config/initializers/locale.rb
# tell the I18n library where to find your translations
I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')]
# set default locale to something other than :en
I18n.default_locale = :en
检查 I18n.available_locales 返回的内容,nil或locales。你正在使用的切换菜单似乎很好。它也会这样工作。
如果你能更具体地解释你的问题,也许我可以提供帮助。 谢谢。
编辑:
这样就足以让您的视图具有切换语言链接。
<% if I18n.locale == I18n.default_locale %>
<li><%= link_to image_tag("swe.png", :alt => "Sweden", :class =>"round"), "http://www.natkurser.se" %> %>
<li><h5><%= link_to_unless I18n.locale == :se, "Swedish", "#{'http://www.natkurser.se'}" %></h5>
<% else %>
<li><%= link_to image_tag("eng.png", :alt => "England", :class =>"round"), "http://gettheskill.com" %>
<li><h5><%= link_to_unless I18n.locale == :en, "English", "#{'http://gettheskill.com'}" %></h5>
<%end%>