在当前页面切换语言环境 rails
Switch locale on current page rails
我目前正在从事一个项目,该项目有 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
我有很多 link 需要翻译,所以我希望有一个轨道可以做到这一点。
您可以将资源传递给 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
我目前正在从事一个项目,该项目有 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
我有很多 link 需要翻译,所以我希望有一个轨道可以做到这一点。
您可以将资源传递给 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