<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # Rails 國際化 API Rails 內建支持 Ruby I18n(internationalization 的簡寫)。Ruby I18n 這個 gem 用法簡單,是個擴展性強的框架,可以把程序翻譯成英語之外的其他語言,或者為程序提供多種語言支持。 “國際化”是指把程序中的字符串或者其他需要本地化的內容(例如,日期和貨幣的格式)提取出來的過程。“本地化”是指把提取出來的內容翻譯成本地語言或者本地所用格式的過程。 所以在 Rails 程序國際化的過程中要做這些事情: * 確保程序支持 i18n; * 告訴 Rails 在哪里尋找本地語言包; * 告訴 Rails 怎么設置、保存和切換本地語言包; 在本地化程序的過程中或許要做以下三件事: * 修改或提供 Rails 默認使用的本地語言包,例如,日期和時間的格式、月份名、Active Record 模型名等; * 把程序中的字符串提取出來,保存到鍵值對中,例如 Flash 消息、視圖中的純文本等; * 在某個地方保存語言包; 本文會詳細介紹 I18n API,并提供一個教程,演示如何從頭開始國際化一個 Rails 程序。 讀完本文,你將學到: * Ruby on Rails 是如何處理 i18n 的; * 如何在 REST 架構的程序中正確使用 i18n; * 如何使用 i18n 翻譯 ActiveRecord 錯誤和 ActionMailer E-mail; * 協助翻譯程序的工具; ### Chapters 1. [Ruby on Rails 是如何處理 i18n 的](#ruby-on-rails-%E6%98%AF%E5%A6%82%E4%BD%95%E5%A4%84%E7%90%86-i18n-%E7%9A%84) * [Ruby I18n 的整體架構](#ruby-i18n-%E7%9A%84%E6%95%B4%E4%BD%93%E6%9E%B6%E6%9E%84) * [公開 API](#%E5%85%AC%E5%BC%80-api) 2. [為國際化做準備](#%E4%B8%BA%E5%9B%BD%E9%99%85%E5%8C%96%E5%81%9A%E5%87%86%E5%A4%87) * [配置 I18n 模塊](#%E9%85%8D%E7%BD%AE-i18n-%E6%A8%A1%E5%9D%97) * [(選做)更改 I18n 庫的設置](#%EF%BC%88%E9%80%89%E5%81%9A%EF%BC%89%E6%9B%B4%E6%94%B9-i18n-%E5%BA%93%E7%9A%84%E8%AE%BE%E7%BD%AE) * [設置并傳入所用語言](#%E8%AE%BE%E7%BD%AE%E5%B9%B6%E4%BC%A0%E5%85%A5%E6%89%80%E7%94%A8%E8%AF%AD%E8%A8%80) * [使用不同的域名加載不同的語言](#%E4%BD%BF%E7%94%A8%E4%B8%8D%E5%90%8C%E7%9A%84%E5%9F%9F%E5%90%8D%E5%8A%A0%E8%BD%BD%E4%B8%8D%E5%90%8C%E7%9A%84%E8%AF%AD%E8%A8%80) * [在 URL 參數中設置所用語言](#%E5%9C%A8-url-%E5%8F%82%E6%95%B0%E4%B8%AD%E8%AE%BE%E7%BD%AE%E6%89%80%E7%94%A8%E8%AF%AD%E8%A8%80) * [Setting the Locale from the Client Supplied Information](#setting-the-locale-from-the-client-supplied-information) 3. [Internationalizing your Application](#internationalizing-your-application) * [Adding Translations](#adding-translations) * [Passing variables to translations](#passing-variables-to-translations) * [Adding Date/Time Formats](#adding-date/time-formats) * [Inflection Rules For Other Locales](#inflection-rules-for-other-locales) * [Localized Views](#localized-views) * [Organization of Locale Files](#organization-of-locale-files) 4. [Overview of the I18n API Features](#overview-of-the-i18n-api-features) * [Looking up Translations](#looking-up-translations) * [Interpolation](#interpolation) * [Pluralization](#pluralization) * [Setting and Passing a Locale](#setting-and-passing-a-locale) * [Using Safe HTML Translations](#using-safe-html-translations) 5. [How to Store your Custom Translations](#how-to-store-your-custom-translations) * [Translations for Active Record Models](#translations-for-active-record-models) * [Translations for Action Mailer E-Mail Subjects](#translations-for-action-mailer-e-mail-subjects) * [Overview of Other Built-In Methods that Provide I18n Support](#overview-of-other-built-in-methods-that-provide-i18n-support) 6. [Customize your I18n Setup](#customize-your-i18n-setup) * [Using Different Backends](#using-different-backends) * [Using Different Exception Handlers](#using-different-exception-handlers) 7. [Conclusion](#conclusion) 8. [Contributing to Rails I18n](#contributing-to-rails-i18n) 9. [Resources](#resources) 10. [Authors](#authors) 11. [Footnotes](#footnotes) Ruby I18n 框架提供了 Rails 程序國際化和本地化所需的各種功能。不過,還可以使用各種插件和擴展,添加額外的功能。詳情參見 [Ruby I18n 的維基](http://ruby-i18n.org/wiki)。 ### 1 Ruby on Rails 是如何處理 i18n 的 國際化是個很復雜的問題。自然語言千差萬別(例如復數變形規則),很難提供一種工具解決所有問題。因此,Rails I18n API 只關注: * 默認支持和英語類似的語言; * 讓支持其他語言變得簡單; Rails 框架中的每個靜態字符串(例如,Active Record 數據驗證消息,日期和時間的格式)都支持國際化,因此本地化時只要重寫默認值即可。 #### 1.1 Ruby I18n 的整體架構 Ruby I18n 分成兩部分: * 公開的 API:這是一個 Ruby 模塊,定義了庫中可用的公開方法; * 一個默認的后臺(特意取名為“Simple”),實現這些方法; 普通用戶只要使用這些公開方法即可,但了解后臺的功能也有助于使用 i18n API。 默認提供的“Simple”后臺可以用其他強大的后臺替代(推薦這么做),例如把翻譯后的數據存儲在關系型數據庫中,或 GetText 語言包中。詳情參見下文的“[使用其他后臺](#using-different-backends)”一節。 #### 1.2 公開 API I18n API 最重要的方法是: ``` translate # Lookup text translations localize # Localize Date and Time objects to local formats ``` 這兩個方法都有別名,分別為 `#t` 和 `#l`。因此可以這么用: ``` I18n.t 'store.title' I18n.l Time.now ``` I18n API 同時還提供了針對下述屬性的讀取和設值方法: ``` load_path # Announce your custom translation files locale # Get and set the current locale default_locale # Get and set the default locale exception_handler # Use a different exception_handler backend # Use a different backend ``` 下一節起,我們要從零開始國際化一個簡單的 Rails 程序。 ### 2 為國際化做準備 為程序提供 I18n 支持只需簡單幾步。 #### 2.1 配置 I18n 模塊 按照“多約定,少配置”原則,Rails 會為程序提供一些合理的默認值。如果想使用其他設置,可以很容易的改寫默認值。 Rails 會自動把 `config/locales` 文件夾中所有 `.rb` 和 `.yml` 文件加入**譯文加載路徑**。 默認提供的 `en.yml` 文件中包含一些簡單的翻譯文本: ``` en: hello: "Hello world" ``` 上面這段代碼的意思是,在 `:en` 語言中,`hello` 鍵映射到字符串 `"Hello world"` 上。Rails 中的每個字符串的國際化都使用這種方式,比如說 Active Model [數據驗證消息](https://github.com/rails/rails/blob/master/activemodel/lib/active_model/locale/en.yml)以及[日期和時間格式](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml)。在默認的后臺中,可以使用 YAML 或標準的 Ruby Hash 存儲翻譯數據。 I18n 庫使用的默認語言是**英語**,所以如果沒設為其他語言,就會用 `:en` 查找翻譯數據。 經過[討論](http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en)之后,i18n 庫決定為語言名稱使用一種**務實的方案**,只說明所用語言(例如,`:en`,`:pl`),不區分地區(例如,`:en-US`,`:en-GB`)。地區經常用來區分同一語言在不同地區的分支或者方言。很多國際化程序只使用語言名稱,例如 `:cs`、`:th` 和 `:es`(分別為捷克語,泰語和西班牙語)。不過,同一語種在不同地區可能有重要差別。例如,在 `:en-US` 中,貨幣符號是“$”,但在 `:en-GB` 中是“£”。在 Rails 中使用區分地區的語言設置也是可行的,只要在 `:en-GB` 中使用完整的“English - United Kingdom”即可。很多 [Rails I18n 插件](http://rails-i18n.org/wiki),例如 [Globalize3](https://github.com/globalize/globalize),都可以實現。 **譯文加載路徑**(`I18n.load_path`)是一個 Ruby 數組,由譯文文件的路徑組成,Rails 程序會自動加載這些文件。你可以使用任何一個文件夾,任何一種文件命名方式。 首次加載查找譯文時,后臺會惰性加載這些譯文。這么做即使已經聲明過,也可以更換所用后臺。 `application.rb` 文件中的默認內容有介紹如何從其他文件夾中添加本地數據,以及如何設置默認使用的語言。去掉相關代碼行前面的注釋,修改即可。 ``` # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de ``` #### 2.2 (選做)更改 I18n 庫的設置 如果基于某些原因不想使用 `application.rb` 文件中的設置,我們來介紹一下手動設置的方法。 告知 I18n 庫在哪里尋找譯文文件,可以在程序的任何地方指定加載路徑。但要保證這個設置要在加載譯文之前執行。我們可能還要修改默認使用的語言。要完成這兩個設置,最簡單的方法是把下面的代碼放到一個初始化腳本中: ``` # in config/initializers/locale.rb # tell the I18n library where to find your translations I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')] # set default locale to something other than :en I18n.default_locale = :pt ``` #### 2.3 設置并傳入所用語言 如果想把 Rails 程序翻譯成英語(默認語言)之外的其他語言,可以在 `application.rb` 文件或初始化腳本中設置 `I18n.default_locale` 選項。這個設置對所有請求都有效。 不過,或許你希望為程序提供多種語言支持。此時,需要在請求中指定所用語言。 你可能想過把用戶選擇適用的語言保存在會話或 cookie 中,請**千萬別**這么做。所用語言應該是透明的,寫在 URL 中。這樣做不會破壞用戶對網頁內容的預想,如果把 URL 發給一個朋友,他應該看到和我相同的內容。這種方式在 [REST 架構](http://en.wikipedia.org/wiki/Representational_State_Transfer)中很容易實現。不過也有不適用 REST 架構的情況,后文會說明。 設置所用語言的方法很簡單,只需在 `ApplicationController` 的 `before_action` 中作如下設定即可: ``` before_action :set_locale def set_locale I18n.locale = params[:locale] || I18n.default_locale end ``` 使用這種方法要把語言作為 URL 查詢參數傳入,例如 `http://example.com/books?locale=pt`(這是 Google 使用的方法)。`http://localhost:3000?locale=pt` 會加載葡萄牙語,`http://localhost:3000?locale=de` 會加載德語,以此類推。如果想手動在 URL 中指定語言再刷新頁面,可以跳過后面幾小節,直接閱讀“[國際化程序](#internationalizing-your-application)”一節。 當然了,你可能并不想手動在每個 URL 中指定語言,或者想使用其他形式的 URL,例如 `http://example.com/pt/books` 或 `http://example.com/en/books`。下面分別介紹其他各種設置語言的方法。 #### 2.4 使用不同的域名加載不同的語言 設置所用語言可以通過不同的域名實現。例如,`www.example.com` 加載英語內容,`www.example.es` 加載西班牙語內容。這里使用的是不同的頂級域名。這么做有多個好處: * 所用語言在 URL 中很明顯; * 用戶很容易得知所查看內容使用的語言; * 在 Rails 中可以輕松實現; * 搜索引擎似乎喜歡把不同語言的內容放在不同但相互關聯的域名上; 在 `ApplicationController` 中加入如下代碼可以實現這種處理方式: ``` before_action :set_locale def set_locale I18n.locale = extract_locale_from_tld || I18n.default_locale end # Get locale from top-level domain or return nil if such locale is not available # You have to put something like: # 127.0.0.1 application.com # 127.0.0.1 application.it # 127.0.0.1 application.pl # in your /etc/hosts file to try this out locally def extract_locale_from_tld parsed_locale = request.host.split('.').last I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil end ``` 類似地,還可以使用不同的二級域名提供不同語言的內容: ``` # Get locale code from request subdomain (like http://it.application.local:3000) # You have to put something like: # 127.0.0.1 gr.application.local # in your /etc/hosts file to try this out locally def extract_locale_from_subdomain parsed_locale = request.subdomains.first I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil end ``` 如果程序中需要切換語言的連接,可以這么寫: ``` link_to("Deutsch", "#{APP_CONFIG[:deutsch_website_url]}#{request.env['REQUEST_URI']}") ``` 上述代碼假設 `APP_CONFIG[:deutsch_website_url]` 的值為 `http://www.application.de`。 這種方法雖有種種好處,但你或許不想在不同的域名上提供不同語言的內容。最好的實現方式肯定是在 URL 的參數中加上語言代碼。 #### 2.5 在 URL 參數中設置所用語言 The most usual way of setting (and passing) the locale would be to include it in URL params, as we did in the `I18n.locale = params[:locale]` _before_action_ in the first example. We would like to have URLs like `www.example.com/books?locale=ja` or `www.example.com/ja/books` in this case. This approach has almost the same set of advantages as setting the locale from the domain name: namely that it's RESTful and in accord with the rest of the World Wide Web. It does require a little bit more work to implement, though. Getting the locale from `params` and setting it accordingly is not hard; including it in every URL and thus **passing it through the requests** is. To include an explicit option in every URL (e.g. `link_to( books_url(locale: I18n.locale))`) would be tedious and probably impossible, of course. Rails contains infrastructure for "centralizing dynamic decisions about the URLs" in its [`ApplicationController#default_url_options`](http://api.rubyonrails.org/classes/ActionController/Base.html#M000515), which is useful precisely in this scenario: it enables us to set "defaults" for [`url_for`](http://api.rubyonrails.org/classes/ActionController/Base.html#M000503) and helper methods dependent on it (by implementing/overriding this method). We can include something like this in our `ApplicationController` then: ``` # app/controllers/application_controller.rb def default_url_options(options={}) logger.debug "default_url_options is passed options: #{options.inspect}\n" { locale: I18n.locale } end ``` Every helper method dependent on `url_for` (e.g. helpers for named routes like `root_path` or `root_url`, resource routes like `books_path` or `books_url`, etc.) will now **automatically include the locale in the query string**, like this: `http://localhost:3001/?locale=ja`. You may be satisfied with this. It does impact the readability of URLs, though, when the locale "hangs" at the end of every URL in your application. Moreover, from the architectural standpoint, locale is usually hierarchically above the other parts of the application domain: and URLs should reflect this. You probably want URLs to look like this: `www.example.com/en/books` (which loads the English locale) and `www.example.com/nl/books` (which loads the Dutch locale). This is achievable with the "over-riding `default_url_options`" strategy from above: you just have to set up your routes with [`scoping`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html) option in this way: ``` # config/routes.rb scope "/:locale" do resources :books end ``` Now, when you call the `books_path` method you should get `"/en/books"` (for the default locale). An URL like `http://localhost:3001/nl/books` should load the Dutch locale, then, and following calls to `books_path` should return `"/nl/books"` (because the locale changed). If you don't want to force the use of a locale in your routes you can use an optional path scope (denoted by the parentheses) like so: ``` # config/routes.rb scope "(:locale)", locale: /en|nl/ do resources :books end ``` With this approach you will not get a `Routing Error` when accessing your resources such as `http://localhost:3001/books` without a locale. This is useful for when you want to use the default locale when one is not specified. Of course, you need to take special care of the root URL (usually "homepage" or "dashboard") of your application. An URL like `http://localhost:3001/nl` will not work automatically, because the `root to: "books#index"` declaration in your `routes.rb` doesn't take locale into account. (And rightly so: there's only one "root" URL.) You would probably need to map URLs like these: ``` # config/routes.rb get '/:locale' => 'dashboard#index' ``` Do take special care about the **order of your routes**, so this route declaration does not "eat" other ones. (You may want to add it directly before the `root :to` declaration.) Have a look at two plugins which simplify work with routes in this way: Sven Fuchs's [routing_filter](https://github.com/svenfuchs/routing-filter/tree/master) and Raul Murciano's [translate_routes](https://github.com/raul/translate_routes/tree/master). #### 2.6 Setting the Locale from the Client Supplied Information In specific cases, it would make sense to set the locale from client-supplied information, i.e. not from the URL. This information may come for example from the users' preferred language (set in their browser), can be based on the users' geographical location inferred from their IP, or users can provide it simply by choosing the locale in your application interface and saving it to their profile. This approach is more suitable for web-based applications or services, not for websites - see the box about _sessions_, _cookies_ and RESTful architecture above. ##### 2.6.1 Using `Accept-Language` One source of client supplied information would be an `Accept-Language` HTTP header. People may [set this in their browser](http://www.w3.org/International/questions/qa-lang-priorities) or other clients (such as _curl_). A trivial implementation of using an `Accept-Language` header would be: ``` def set_locale logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}" I18n.locale = extract_locale_from_accept_language_header logger.debug "* Locale set to '#{I18n.locale}'" end private def extract_locale_from_accept_language_header request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first end ``` Of course, in a production environment you would need much more robust code, and could use a plugin such as Iain Hecker's [http_accept_language](https://github.com/iain/http_accept_language/tree/master) or even Rack middleware such as Ryan Tomayko's [locale](https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/locale.rb). ##### 2.6.2 Using GeoIP (or Similar) Database Another way of choosing the locale from client information would be to use a database for mapping the client IP to the region, such as [GeoIP Lite Country](http://www.maxmind.com/app/geolitecountry). The mechanics of the code would be very similar to the code above - you would need to query the database for the user's IP, and look up your preferred locale for the country/region/city returned. ##### 2.6.3 User Profile You can also provide users of your application with means to set (and possibly over-ride) the locale in your application interface, as well. Again, mechanics for this approach would be very similar to the code above - you'd probably let users choose a locale from a dropdown list and save it to their profile in the database. Then you'd set the locale to this value. ### 3 Internationalizing your Application OK! Now you've initialized I18n support for your Ruby on Rails application and told it which locale to use and how to preserve it between requests. With that in place, you're now ready for the really interesting stuff. Let's _internationalize_ our application, i.e. abstract every locale-specific parts, and then _localize_ it, i.e. provide necessary translations for these abstracts. You most probably have something like this in one of your applications: ``` # config/routes.rb Yourapp::Application.routes.draw do root to: "home#index" end ``` ``` # app/controllers/application_controller.rb class ApplicationController < ActionController::Base before_action :set_locale def set_locale I18n.locale = params[:locale] || I18n.default_locale end end ``` ``` # app/controllers/home_controller.rb class HomeController < ApplicationController def index flash[:notice] = "Hello Flash" end end ``` ``` # app/views/home/index.html.erb <h1>Hello World</h1> <p><%= flash[:notice] %></p> ``` ![rails i18n demo untranslated](https://box.kancloud.cn/2016-05-11_573330cd24f48.png) #### 3.1 Adding Translations Obviously there are **two strings that are localized to English**. In order to internationalize this code, **replace these strings** with calls to Rails' `#t` helper with a key that makes sense for the translation: ``` # app/controllers/home_controller.rb class HomeController < ApplicationController def index flash[:notice] = t(:hello_flash) end end ``` ``` # app/views/home/index.html.erb <h1><%=t :hello_world %></h1> <p><%= flash[:notice] %></p> ``` When you now render this view, it will show an error message which tells you that the translations for the keys `:hello_world` and `:hello_flash` are missing. ![rails i18n demo translation missing](https://box.kancloud.cn/2016-05-11_5733310933dbe.png) Rails adds a `t` (`translate`) helper method to your views so that you do not need to spell out `I18n.t` all the time. Additionally this helper will catch missing translations and wrap the resulting error message into a `&lt;span class="translation_missing"&gt;`. So let's add the missing translations into the dictionary files (i.e. do the "localization" part): ``` # config/locales/en.yml en: hello_world: Hello world! hello_flash: Hello flash! # config/locales/pirate.yml pirate: hello_world: Ahoy World hello_flash: Ahoy Flash ``` There you go. Because you haven't changed the default_locale, I18n will use English. Your application now shows: ![rails i18n demo translated to English](https://box.kancloud.cn/2016-05-11_5733310945baf.png) And when you change the URL to pass the pirate locale (`http://localhost:3000?locale=pirate`), you'll get: ![rails i18n demo translated to pirate](https://box.kancloud.cn/2016-05-11_5733310957832.png) You need to restart the server when you add new locale files. You may use YAML (`.yml`) or plain Ruby (`.rb`) files for storing your translations in SimpleStore. YAML is the preferred option among Rails developers. However, it has one big disadvantage. YAML is very sensitive to whitespace and special characters, so the application may not load your dictionary properly. Ruby files will crash your application on first request, so you may easily find what's wrong. (If you encounter any "weird issues" with YAML dictionaries, try putting the relevant portion of your dictionary into a Ruby file.) #### 3.2 Passing variables to translations You can use variables in the translation messages and pass their values from the view. ``` # app/views/home/index.html.erb <%=t 'greet_username', user: "Bill", message: "Goodbye" %> ``` ``` # config/locales/en.yml en: greet_username: "%{message}, %{user}!" ``` #### 3.3 Adding Date/Time Formats OK! Now let's add a timestamp to the view, so we can demo the **date/time localization** feature as well. To localize the time format you pass the Time object to `I18n.l` or (preferably) use Rails' `#l` helper. You can pick a format by passing the `:format` option - by default the `:default` format is used. ``` # app/views/home/index.html.erb <h1><%=t :hello_world %></h1> <p><%= flash[:notice] %></p <p><%= l Time.now, format: :short %></p> ``` And in our pirate translations file let's add a time format (it's already there in Rails' defaults for English): ``` # config/locales/pirate.yml pirate: time: formats: short: "arrrround %H'ish" ``` So that would give you: ![rails i18n demo localized time to pirate](https://box.kancloud.cn/2016-05-11_57333109670a3.png) Right now you might need to add some more date/time formats in order to make the I18n backend work as expected (at least for the 'pirate' locale). Of course, there's a great chance that somebody already did all the work by **translating Rails' defaults for your locale**. See the [rails-i18n repository at GitHub](https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale) for an archive of various locale files. When you put such file(s) in `config/locales/` directory, they will automatically be ready for use. #### 3.4 Inflection Rules For Other Locales Rails allows you to define inflection rules (such as rules for singularization and pluralization) for locales other than English. In `config/initializers/inflections.rb`, you can define these rules for multiple locales. The initializer contains a default example for specifying additional rules for English; follow that format for other locales as you see fit. #### 3.5 Localized Views Let's say you have a _BooksController_ in your application. Your _index_ action renders content in `app/views/books/index.html.erb` template. When you put a _localized variant_ of this template: `index.es.html.erb` in the same directory, Rails will render content in this template, when the locale is set to `:es`. When the locale is set to the default locale, the generic `index.html.erb` view will be used. (Future Rails versions may well bring this _automagic_ localization to assets in `public`, etc.) You can make use of this feature, e.g. when working with a large amount of static content, which would be clumsy to put inside YAML or Ruby dictionaries. Bear in mind, though, that any change you would like to do later to the template must be propagated to all of them. #### 3.6 Organization of Locale Files When you are using the default SimpleStore shipped with the i18n library, dictionaries are stored in plain-text files on the disc. Putting translations for all parts of your application in one file per locale could be hard to manage. You can store these files in a hierarchy which makes sense to you. For example, your `config/locales` directory could look like this: ``` |-defaults |---es.rb |---en.rb |-models |---book |-----es.rb |-----en.rb |-views |---defaults |-----es.rb |-----en.rb |---books |-----es.rb |-----en.rb |---users |-----es.rb |-----en.rb |---navigation |-----es.rb |-----en.rb ``` This way, you can separate model and model attribute names from text inside views, and all of this from the "defaults" (e.g. date and time formats). Other stores for the i18n library could provide different means of such separation. The default locale loading mechanism in Rails does not load locale files in nested dictionaries, like we have here. So, for this to work, we must explicitly tell Rails to look further: ``` # config/application.rb config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')] ``` Do check the [Rails i18n Wiki](http://rails-i18n.org/wiki) for list of tools available for managing translations. ### 4 Overview of the I18n API Features You should have good understanding of using the i18n library now, knowing all necessary aspects of internationalizing a basic Rails application. In the following chapters, we'll cover it's features in more depth. These chapters will show examples using both the `I18n.translate` method as well as the [`translate` view helper method](http://api.rubyonrails.org/classes/ActionView/Helpers/TranslationHelper.html#method-i-translate) (noting the additional feature provide by the view helper method). Covered are features like these: * looking up translations * interpolating data into translations * pluralizing translations * using safe HTML translations (view helper method only) * localizing dates, numbers, currency, etc. #### 4.1 Looking up Translations ##### 4.1.1 Basic Lookup, Scopes and Nested Keys Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent: ``` I18n.t :message I18n.t 'message' ``` The `translate` method also takes a `:scope` option which can contain one or more additional keys that will be used to specify a "namespace" or scope for a translation key: ``` I18n.t :record_invalid, scope: [:activerecord, :errors, :messages] ``` This looks up the `:record_invalid` message in the Active Record error messages. Additionally, both the key and scopes can be specified as dot-separated keys as in: ``` I18n.translate "activerecord.errors.messages.record_invalid" ``` Thus the following calls are equivalent: ``` I18n.t 'activerecord.errors.messages.record_invalid' I18n.t 'errors.messages.record_invalid', scope: :active_record I18n.t :record_invalid, scope: 'activerecord.errors.messages' I18n.t :record_invalid, scope: [:activerecord, :errors, :messages] ``` ##### 4.1.2 Defaults When a `:default` option is given, its value will be returned if the translation is missing: ``` I18n.t :missing, default: 'Not here' # => 'Not here' ``` If the `:default` value is a Symbol, it will be used as a key and translated. One can provide multiple values as default. The first one that results in a value will be returned. E.g., the following first tries to translate the key `:missing` and then the key `:also_missing.` As both do not yield a result, the string "Not here" will be returned: ``` I18n.t :missing, default: [:also_missing, 'Not here'] # => 'Not here' ``` ##### 4.1.3 Bulk and Namespace Lookup To look up multiple translations at once, an array of keys can be passed: ``` I18n.t [:odd, :even], scope: 'errors.messages' # => ["must be odd", "must be even"] ``` Also, a key can translate to a (potentially nested) hash of grouped translations. E.g., one can receive _all_ Active Record error messages as a Hash with: ``` I18n.t 'activerecord.errors.messages' # => {:inclusion=>"is not included in the list", :exclusion=> ... } ``` ##### 4.1.4 "Lazy" Lookup Rails implements a convenient way to look up the locale inside _views_. When you have the following dictionary: ``` es: books: index: title: "Título" ``` you can look up the `books.index.title` value **inside** `app/views/books/index.html.erb` template like this (note the dot): ``` <%= t '.title' %> ``` Automatic translation scoping by partial is only available from the `translate` view helper method. #### 4.2 Interpolation In many cases you want to abstract your translations so that **variables can be interpolated into the translation**. For this reason the I18n API provides an interpolation feature. All options besides `:default` and `:scope` that are passed to `#translate` will be interpolated to the translation: ``` I18n.backend.store_translations :en, thanks: 'Thanks %{name}!' I18n.translate :thanks, name: 'Jeremy' # => 'Thanks Jeremy!' ``` If a translation uses `:default` or `:scope` as an interpolation variable, an `I18n::ReservedInterpolationKey` exception is raised. If a translation expects an interpolation variable, but this has not been passed to `#translate`, an `I18n::MissingInterpolationArgument` exception is raised. #### 4.3 Pluralization In English there are only one singular and one plural form for a given string, e.g. "1 message" and "2 messages". Other languages ([Arabic](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ar), [Japanese](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ja), [Russian](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ru) and many more) have different grammars that have additional or fewer [plural forms](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html). Thus, the I18n API provides a flexible pluralization feature. The `:count` interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR: ``` I18n.backend.store_translations :en, inbox: { one: 'one message', other: '%{count} messages' } I18n.translate :inbox, count: 2 # => '2 messages' I18n.translate :inbox, count: 1 # => 'one message' ``` The algorithm for pluralizations in `:en` is as simple as: ``` entry[count == 1 ? 0 : 1] ``` I.e. the translation denoted as `:one` is regarded as singular, the other is used as plural (including the count being zero). If the lookup for the key does not return a Hash suitable for pluralization, an `18n::InvalidPluralizationData` exception is raised. #### 4.4 Setting and Passing a Locale The locale can be either set pseudo-globally to `I18n.locale` (which uses `Thread.current` like, e.g., `Time.zone`) or can be passed as an option to `#translate` and `#localize`. If no locale is passed, `I18n.locale` is used: ``` I18n.locale = :de I18n.t :foo I18n.l Time.now ``` Explicitly passing a locale: ``` I18n.t :foo, locale: :de I18n.l Time.now, locale: :de ``` The `I18n.locale` defaults to `I18n.default_locale` which defaults to :`en`. The default locale can be set like this: ``` I18n.default_locale = :de ``` #### 4.5 Using Safe HTML Translations Keys with a '_html' suffix and keys named 'html' are marked as HTML safe. When you use them in views the HTML will not be escaped. ``` # config/locales/en.yml en: welcome: <b>welcome!</b> hello_html: <b>hello!</b> title: html: <b>title!</b> ``` ``` # app/views/home/index.html.erb <div><%= t('welcome') %></div> <div><%= raw t('welcome') %></div> <div><%= t('hello_html') %></div> <div><%= t('title.html') %></div> ``` Automatic conversion to HTML safe translate text is only available from the `translate` view helper method. ![i18n demo html safe](https://box.kancloud.cn/2016-05-11_5733310978cb7.png) ### 5 How to Store your Custom Translations The Simple backend shipped with Active Support allows you to store translations in both plain Ruby and YAML format.&lt;sup class="footnote" id="footnote-2-ref"&gt;[2](#footnote-2)&lt;/sup&gt; For example a Ruby Hash providing translations can look like this: ``` { pt: { foo: { bar: "baz" } } } ``` The equivalent YAML file would look like this: ``` pt: foo: bar: baz ``` As you see, in both cases the top level key is the locale. `:foo` is a namespace key and `:bar` is the key for the translation "baz". Here is a "real" example from the Active Support `en.yml` translations YAML file: ``` en: date: formats: default: "%Y-%m-%d" short: "%b %d" long: "%B %d, %Y" ``` So, all of the following equivalent lookups will return the `:short` date format `"%b %d"`: ``` I18n.t 'date.formats.short' I18n.t 'formats.short', scope: :date I18n.t :short, scope: 'date.formats' I18n.t :short, scope: [:date, :formats] ``` Generally we recommend using YAML as a format for storing translations. There are cases, though, where you want to store Ruby lambdas as part of your locale data, e.g. for special date formats. #### 5.1 Translations for Active Record Models You can use the methods `Model.model_name.human` and `Model.human_attribute_name(attribute)` to transparently look up translations for your model and attribute names. For example when you add the following translations: ``` en: activerecord: models: user: Dude attributes: user: login: "Handle" # will translate User attribute "login" as "Handle" ``` Then `User.model_name.human` will return "Dude" and `User.human_attribute_name("login")` will return "Handle". You can also set a plural form for model names, adding as following: ``` en: activerecord: models: user: one: Dude other: Dudes ``` Then `User.model_name.human(count: 2)` will return "Dudes". With `count: 1` or without params will return "Dude". ##### 5.1.1 Error Message Scopes Active Record validation error messages can also be translated easily. Active Record gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes, and/or validations. It also transparently takes single table inheritance into account. This gives you quite powerful means to flexibly adjust your messages to your application's needs. Consider a User model with a validation for the name attribute like this: ``` class User < ActiveRecord::Base validates :name, presence: true end ``` The key for the error message in this case is `:blank`. Active Record will look up this key in the namespaces: ``` activerecord.errors.models.[model_name].attributes.[attribute_name] activerecord.errors.models.[model_name] activerecord.errors.messages errors.attributes.[attribute_name] errors.messages ``` Thus, in our example it will try the following keys in this order and return the first result: ``` activerecord.errors.models.user.attributes.name.blank activerecord.errors.models.user.blank activerecord.errors.messages.blank errors.attributes.name.blank errors.messages.blank ``` When your models are additionally using inheritance then the messages are looked up in the inheritance chain. For example, you might have an Admin model inheriting from User: ``` class Admin < User validates :name, presence: true end ``` Then Active Record will look for messages in this order: ``` activerecord.errors.models.admin.attributes.name.blank activerecord.errors.models.admin.blank activerecord.errors.models.user.attributes.name.blank activerecord.errors.models.user.blank activerecord.errors.messages.blank errors.attributes.name.blank errors.messages.blank ``` This way you can provide special translations for various error messages at different points in your models inheritance chain and in the attributes, models, or default scopes. ##### 5.1.2 Error Message Interpolation The translated model name, translated attribute name, and value are always available for interpolation. So, for example, instead of the default error message `"cannot be blank"` you could use the attribute name like this : `"Please fill in your %{attribute}"`. * `count`, where available, can be used for pluralization if present: | validation | with option | message | interpolation | | --- | --- | --- | --- | | confirmation | - | :confirmation | - | | acceptance | - | :accepted | - | | presence | - | :blank | - | | absence | - | :present | - | | length | :within, :in | :too_short | count | | length | :within, :in | :too_long | count | | length | :is | :wrong_length | count | | length | :minimum | :too_short | count | | length | :maximum | :too_long | count | | uniqueness | - | :taken | - | | format | - | :invalid | - | | inclusion | - | :inclusion | - | | exclusion | - | :exclusion | - | | associated | - | :invalid | - | | numericality | - | :not_a_number | - | | numericality | :greater_than | :greater_than | count | | numericality | :greater_than_or_equal_to | :greater_than_or_equal_to | count | | numericality | :equal_to | :equal_to | count | | numericality | :less_than | :less_than | count | | numericality | :less_than_or_equal_to | :less_than_or_equal_to | count | | numericality | :only_integer | :not_an_integer | - | | numericality | :odd | :odd | - | | numericality | :even | :even | - | ##### 5.1.3 Translations for the Active Record `error_messages_for` Helper If you are using the Active Record `error_messages_for` helper, you will want to add translations for it. Rails ships with the following translations: ``` en: activerecord: errors: template: header: one: "1 error prohibited this %{model} from being saved" other: "%{count} errors prohibited this %{model} from being saved" body: "There were problems with the following fields:" ``` In order to use this helper, you need to install [DynamicForm](https://github.com/joelmoss/dynamic_form) gem by adding this line to your Gemfile: `gem 'dynamic_form'`. #### 5.2 Translations for Action Mailer E-Mail Subjects If you don't pass a subject to the `mail` method, Action Mailer will try to find it in your translations. The performed lookup will use the pattern `&lt;mailer_scope&gt;.&lt;action_name&gt;.subject` to construct the key. ``` # user_mailer.rb class UserMailer < ActionMailer::Base def welcome(user) #... end end ``` ``` en: user_mailer: welcome: subject: "Welcome to Rails Guides!" ``` #### 5.3 Overview of Other Built-In Methods that Provide I18n Support Rails uses fixed strings and other localizations, such as format strings and other format information in a couple of helpers. Here's a brief overview. ##### 5.3.1 Action View Helper Methods * `distance_of_time_in_words` translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See [datetime.distance_in_words](https://github.com/rails/rails/blob/master/actionview/lib/action_view/locale/en.yml#L4) translations. * `datetime_select` and `select_month` use translated month names for populating the resulting select tag. See [date.month_names](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15) for translations. `datetime_select` also looks up the order option from [date.order](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18) (unless you pass the option explicitly). All date selection helpers translate the prompt using the translations in the [datetime.prompts](https://github.com/rails/rails/blob/master/actionview/lib/action_view/locale/en.yml#L39) scope if applicable. * The `number_to_currency`, `number_with_precision`, `number_to_percentage`, `number_with_delimiter`, and `number_to_human_size` helpers use the number format settings located in the [number](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L37) scope. ##### 5.3.2 Active Model Methods * `model_name.human` and `human_attribute_name` use translations for model names and attribute names if available in the [activerecord.models](https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L36) scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes". * `ActiveModel::Errors#generate_message` (which is used by Active Model validations but may also be used manually) uses `model_name.human` and `human_attribute_name` (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes". * `ActiveModel::Errors#full_messages` prepends the attribute name to the error message using a separator that will be looked up from [errors.format](https://github.com/rails/rails/blob/master/activemodel/lib/active_model/locale/en.yml#L4) (and which defaults to `"%{attribute} %{message}"`). ##### 5.3.3 Active Support Methods * `Array#to_sentence` uses format settings as given in the [support.array](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L33) scope. ### 6 Customize your I18n Setup #### 6.1 Using Different Backends For several reasons the Simple backend shipped with Active Support only does the "simplest thing that could possibly work" _for Ruby on Rails_&lt;sup class="footnote" id="footnote-3-ref"&gt;[3](#footnote-3)&lt;/sup&gt; ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but cannot dynamically store them to any format. That does not mean you're stuck with these limitations, though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend: ``` I18n.backend = Globalize::Backend::Static.new ``` You can also use the Chain backend to chain multiple backends together. This is useful when you want to use standard translations with a Simple backend but store custom application translations in a database or other backends. For example, you could use the Active Record backend and fall back to the (default) Simple backend: ``` I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend) ``` #### 6.2 Using Different Exception Handlers The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur: ``` MissingTranslationData # no translation was found for the requested key InvalidLocale # the locale set to I18n.locale is invalid (e.g. nil) InvalidPluralizationData # a count option was passed but the translation data is not suitable for pluralization MissingInterpolationArgument # the translation expects an interpolation argument that has not been passed ReservedInterpolationKey # the translation contains a reserved interpolation variable name (i.e. one of: scope, default) UnknownFileType # the backend does not know how to handle a file type that was added to I18n.load_path ``` The I18n API will catch all of these exceptions when they are thrown in the backend and pass them to the default_exception_handler method. This method will re-raise all exceptions except for `MissingTranslationData` exceptions. When a `MissingTranslationData` exception has been caught, it will return the exception's error message string containing the missing key/scope. The reason for this is that during development you'd usually want your views to still render even though a translation is missing. In other contexts you might want to change this behavior, though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module or a class with `#call` method: ``` module I18n class JustRaiseExceptionHandler < ExceptionHandler def call(exception, locale, key, options) if exception.is_a?(MissingTranslation) raise exception.to_exception else super end end end end I18n.exception_handler = I18n::JustRaiseExceptionHandler.new ``` This would re-raise only the `MissingTranslationData` exception, passing all other input to the default exception handler. However, if you are using `I18n::Backend::Pluralization` this handler will also raise `I18n::MissingTranslationData: translation missing: en.i18n.plural.rule` exception that should normally be ignored to fall back to the default pluralization rule for English locale. To avoid this you may use additional check for translation key: ``` if exception.is_a?(MissingTranslation) && key.to_s != 'i18n.plural.rule' raise exception.to_exception else super end ``` Another example where the default behavior is less desirable is the Rails TranslationHelper which provides the method `#t` (as well as `#translate`). When a `MissingTranslationData` exception occurs in this context, the helper wraps the message into a span with the CSS class `translation_missing`. To do so, the helper forces `I18n#translate` to raise exceptions no matter what exception handler is defined by setting the `:raise` option: ``` I18n.t :foo, raise: true # always re-raises exceptions from the backend ``` ### 7 Conclusion At this point you should have a good overview about how I18n support in Ruby on Rails works and are ready to start translating your project. If you find anything missing or wrong in this guide, please file a ticket on our [issue tracker](http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview). If you want to discuss certain portions or have questions, please sign up to our [mailing list](http://groups.google.com/group/rails-i18n). ### 8 Contributing to Rails I18n I18n support in Ruby on Rails was introduced in the release 2.2 and is still evolving. The project follows the good Ruby on Rails development tradition of evolving solutions in plugins and real applications first, and only then cherry-picking the best-of-breed of most widely useful features for inclusion in the core. Thus we encourage everybody to experiment with new ideas and features in plugins or other libraries and make them available to the community. (Don't forget to announce your work on our [mailing list](http://groups.google.com/group/rails-i18n!)) If you find your own locale (language) missing from our [example translations data](https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale) repository for Ruby on Rails, please [_fork_](https://github.com/guides/fork-a-project-and-submit-your-modifications) the repository, add your data and send a [pull request](https://github.com/guides/pull-requests). ### 9 Resources * [rails-i18n.org](http://rails-i18n.org) - Homepage of the rails-i18n project. You can find lots of useful resources on the [wiki](http://rails-i18n.org/wiki). * [Google group: rails-i18n](http://groups.google.com/group/rails-i18n) - The project's mailing list. * [GitHub: rails-i18n](https://github.com/svenfuchs/rails-i18n/tree/master) - Code repository for the rails-i18n project. Most importantly you can find lots of [example translations](https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale) for Rails that should work for your application in most cases. * [GitHub: i18n](https://github.com/svenfuchs/i18n/tree/master) - Code repository for the i18n gem. * [Lighthouse: rails-i18n](http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview) - Issue tracker for the rails-i18n project. * [Lighthouse: i18n](http://i18n.lighthouseapp.com/projects/14947-ruby-i18n/overview) - Issue tracker for the i18n gem. ### 10 Authors * [Sven Fuchs](http://www.workingwithrails.com/person/9963-sven-fuchs) (initial author) * [Karel Mina?ík](http://www.workingwithrails.com/person/7476-karel-mina-k) If you found this guide useful, please consider recommending its authors on [workingwithrails](http://www.workingwithrails.com). ### 11 Footnotes [&lt;sup&gt;1&lt;/sup&gt;](#footnote-1-ref) Or, to quote [Wikipedia](http://en.wikipedia.org/wiki/Internationalization_and_localization): _"Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text."_ [&lt;sup&gt;2&lt;/sup&gt;](#footnote-2-ref) Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files. [&lt;sup&gt;3&lt;/sup&gt;](#footnote-3-ref) One of these reasons is that we don't want to imply any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions. ### 反饋 歡迎幫忙改善指南質量。 如發現任何錯誤,歡迎修正。開始貢獻前,可先行閱讀[貢獻指南:文檔](http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation)。 翻譯如有錯誤,深感抱歉,歡迎 [Fork](https://github.com/ruby-china/guides/fork) 修正,或至此處[回報](https://github.com/ruby-china/guides/issues/new)。 文章可能有未完成或過時的內容。請先檢查 [Edge Guides](http://edgeguides.rubyonrails.org) 來確定問題在 master 是否已經修掉了。再上 master 補上缺少的文件。內容參考 [Ruby on Rails 指南準則](ruby_on_rails_guides_guidelines.html)來了解行文風格。 最后,任何關于 Ruby on Rails 文檔的討論,歡迎到 [rubyonrails-docs 郵件群組](http://groups.google.com/group/rubyonrails-docs)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看