Switch locale to current page rails
I am currently working on a project that has 2 different local computers (nl / fr).
We faced this problem: how can i get the translated url for the current page when i display the fr / nl button
I am currently working with friendly_id and globalizing
we tried:
= link_to "nl", params.merge(locale: "nl")
= link_to "nl", url_for(:locale => :nl)
both work to change the current language, but since we have friendly_url when the page is loaded in french (localhost: 3000 / c / animaux)
we must have
localhost:3000/nl/c/dieren
instead
localhost:3000/nl/c/animaux
I have so many links to translate so I want a railsway there.
+3
source to share
1 answer
You can pass url_for resource:
= link_to "nl", params.merge(locale: "nl", id: @resource.id)
If this is too much code duplication, you can create a helper:
# 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
Another option is to use I18n.with_locale
, it allows you to run a block in another language:
I18n.with_locale(:nl) do
link_to('nl', params.merge(id: category.name))
end
+1
source to share