Localization, also known as internationalization is the process of changing the complete site content in some other languages. In Rails 3, all dependencies for localization are already included in i18n library, you only require few codes as given below:
In Application controller, add
before_filter :set_locale
def set_locale
I18n.locale = params[:locale]
end
Add in config/initializers/global.rb (If global.rb is not there, add the file)
I18n.default_locale = :en
I18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
In config/locales, en.yml file is already there with content:
en:
hello: "Hello world"
Add one file, say fr.yml (fr stands for French, but you can name it anything)
fr:
hello: " French Hello world "
Now change any static content in the any view, I am changing 'Username' in login page view with
<%= t('hello')%>
Open the page in browser, http://localhost:3000/login will display 'Hello world' in place of 'Username' because by default locale is set as english in global.rb setting.
Change the url as http://localhost:3000/login?locale=en will display 'Hello world'
Now change the url as http://localhost:3000/login?locale=fr, it will display 'French Hello world'.
This way you can change any static content of the site to any language.
No comments:
Post a Comment