Jon Snow
Jon Snow

Reputation: 11872

how to change locale in URL using Routing Filter gem Rails I18n application?

I installed and set up routing-filter as described on the gem documentation page. https://github.com/svenfuchs/routing-filter

It works for the default locale. For example, if I set up my default locale as :en,the site is in English, and if I set my default locale as :zh, the site is in Chinese.

www.site.com/zh/home (the default locale path /en is automatically added to the URL)

But how can I make my site support BOTH languages?

when the default locale is :zh, I tried to change the URL by substituting the "zh" with "en" but the page is still in Chinese, not English.

Is this something not supported by the routing-filter gem? If not, is there some other gem I can use?

Or have I not set up the routing-filter gem properly?

Thanks!

Upvotes: 1

Views: 1912

Answers (2)

Penguin
Penguin

Reputation: 943

If you want to just switch the locale in current page, then you don't need put in path. just code url_for(:locale => 'de') or url_for(params.merge(:locale => 'ko')) So I code my translate nav like this. May wish save your time with this code:)

<nav id="trans-nav">
    <%= link_to 'KOR', url_for(params.merge(:locale => 'ko')), :class => ('active' if I18n.locale.to_s == 'ko' ) %>
    <%= link_to 'ENG', url_for(params.merge(:locale => 'en')), :class => ('active' if I18n.locale.to_s == 'en' ) %>
    <%= link_to 'CHI', url_for(params.merge(:locale => 'cn')), :class => ('active' if I18n.locale.to_s == 'cn' ) %>
</nav>

or

<nav id="trans-nav">
    <%= link_to 'KOR', url_for(:locale => 'ko'), :class => ('active' if I18n.locale.to_s == 'ko' ) %>
    <%= link_to 'ENG', url_for(:locale => 'en'), :class => ('active' if I18n.locale.to_s == 'en' ) %>
    <%= link_to 'CHI', url_for(:locale => 'cn'), :class => ('active' if I18n.locale.to_s == 'cn' ) %>
</nav>

Upvotes: 0

Jon Snow
Jon Snow

Reputation: 11872

After reading the source-code, I see what this gem is doing.

The following is the comment in the source code.

The Locale filter extracts segments matching /:locale from the beginning of the recognized path and exposes the page parameter as params[:locale]. When a path is generated the filter adds the segments to the path accordingly if the page parameter is passed to the url helper.

incoming url: /de/products
filtered url: /products
params: params[:locale] = 'de'

You can install the filter like this:

# in config/routes.rb
Rails.application.routes.draw do
filter :locale
end

To make your named_route helpers or url_for add the locale segments you can use:

products_path(:locale => 'de')
url_for(:products, :locale => 'de'))

I added the needed logic to application_controller.rb so it's all working.

Upvotes: 3

Related Questions