Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
639 views
in Technique[技术] by (71.8m points)

internationalization - Rails link to current page and passing parameters to it

I am adding I18N to my rails application by passing the locale using url params. My urls are looking like http://example.com/en/users and http://example.com/ar/users (for the english and arabic locales respectively).

In my routes file, I have defined my routes with a :path_prefix option:

map.resources :users, :path_prefix => '/:locale'

And locale is being set using a before_filter defined in ApplicationController

def set_locale
    I18n.locale = params[:locale]
end

I also defined ApplicationController#default_url_options, to add locale to all urls generated by the application:

def default_url_options(options={})
    {:locale => I18n.locale}
end

What I want is to add a link in the layout header (displayed in all pages) that would link to the same page but with the other locale.

For instance, if I am browsing the arabic locale, I want a "English" link in the header, that will redirect me back to my current page, and set the locale to english. Is there a way to do this in rails?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Took me a while to find this but here is my solution:

link_to 'English', url_for( :locale => 'en' )
link_to 'Deutch', url_for( :locale => 'de' ) 

From the docs here: http://api.rubyonrails.org/classes/ActionController/Base.html#M000649

When generating a new URL, missing values may be filled in from the current request‘s parameters. For example, url_for :action => ‘some_action‘ will retain the current controller, as expected. This behavior extends to other parameters, including :controller, :id, and any other parameters that are placed into a Route‘s path.

So using url_for will default to the current request's parameters, just change the one's you want in your code. In this case all I changed was :locale, so everything else stays the same.

Note this also works for "hidden" :parameters. So if you have:

map.my_map ':locale/my_map', :controller => 'home', :action => 'my_map'

using the above url_for in the page /en/my_map will not have 'home' in the url (ie /en/home/my_map). Bonus.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...