【问题标题】:Switch locale on current page rails在当前页面轨道上切换语言环境
【发布时间】:2015-05-29 07:26:31
【问题描述】:

我目前正在从事一个有 2 个不同本地人 (nl/fr) 的项目。

我们面临这个问题:当我显示 fr/nl 按钮时,如何获取当前页面的翻译 url

我目前正在使用friendly_id 和全球化

我们已经试过了:

= link_to "nl", params.merge(locale: "nl")
= link_to "nl", url_for(:locale => :nl)

两者都可以更改当前语言,但正如我们使用friendly_url一样,当页面以法语加载时(localhost:3000/c/animaux)

我们应该有

localhost:3000/nl/c/dieren

而不是

localhost:3000/nl/c/animaux 

我有很多要翻译的链接,所以我希望有一个轨道可以做到这一点。

【问题讨论】:

  • “animaux”是否存储在 slug 列中并来自您的数据库?
  • 对不起,我没有仔细阅读这个问题,它不是重复的。
  • 是的,它使用 globalize 存储在数据库中:表类别: name_fr : animaux | name_nl : dieren
  • @Thounder :那么您是否在每个语言环境中存储友好 url 的副本? name_frname_nl?如果是这样,它是同一个表还是分贝?您是否对所有此类列都遵循相同的模式?例如description_frdescription_nl?
  • @Surya 我正在使用 globalize gem,所以我调用 category.name 并根据当前本地接收到 category.name_frcategory.name_nl 。事实是,当我把链接localhost:3000/c/animaux, local=>nl 放在当前本地仍然“fr”

标签: ruby-on-rails ruby friendly-id globalize


【解决方案1】:

您可以将资源传递给 url_for:

= link_to "nl", params.merge(locale: "nl", id: @resource.id)

如果代码重复过多,您可以创建一个助手:

# Try to guess the resource from controller name
# @param [String] locale
# @param [Hash] options - passed on to url_for
#   @option options [String] :text the text for the link
#   @option options [Object] :resource the model to link to.
def page_in_other_locale(locale, options = {})
  opts = params.dup.merge(options).merge(locale: locale)
  text = opts[:text] || locale     
  resource = nil

  if opts[:resource] 
    resource = opts[:resource]
  else
    resource = controller.instance_variable_get?(":@#{controller_name.singularize}")
  end

  opts.merge!(id: resource.try(:id)) if resource
  link_to(text, opts.except(:text, :resource))
end

另一种选择是使用I18n.with_locale,它可以让你在另一个语言环境中运行一个块:

I18n.with_locale(:nl) do
  link_to('nl', params.merge(id: category.name))
end

【讨论】:

  • 嗯,谢谢你的回答,你给我解决方案的一部分,剩下的我会自己解决。 = link_to "nl", params.merge(locale: "nl", id: @resource.id)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多