gpt4 book ai didi

ruby-on-rails - Rails 国际化 : Setting the Locale from the Domain Name

转载 作者:数据小太阳 更新时间:2023-10-29 08:04:30 25 4
gpt4 key购买 nike

我正在尝试在我的 Rails 应用程序上实现国际化。这是我的应用程序 Controller 的一部分

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 参数设置语言环境,使我在我不使用的 route 使用 scope "(:locale)", locale:/en|se/do不想。

从rails指南上,他们指出切换菜单应该这样实现。

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 国际化文档中似乎遗漏的主要内容。一个详细的答案将不胜感激。

最佳答案

我已遵循 Rails 指南并相应地设置了 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。而且您使用的切换菜单看起来不错。它也会那样工作。

如果您能更具体地解释您的问题,也许我可以提供帮助。谢谢。

编辑:

这足以让您的 View 具有切换语言链接。

<% 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%>

关于ruby-on-rails - Rails 国际化 : Setting the Locale from the Domain Name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20064335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com