rails i18n模型_Rails国际化的完整指南(i18n)
rails i18n模型
by Anastasia
由Anastasia
Rails國際化的完整指南(i18n) (The Complete Guide to Rails Internationalization (i18n))
In this article you are going to learn how to translate your Rails application into multiple languages, work with translations, localize datetime, and switch locales. We are going to see all these aspects in action by creating a sample application and enhancing it step by step. By the end of the article you will have all the necessary knowledge to start implementing these concepts in real projects.
在本文中,您將學(xué)習(xí)如何將Rails應(yīng)用程序翻譯成多種語言,使用翻譯,本地化日期時間以及切換語言環(huán)境。 我們將通過創(chuàng)建示例應(yīng)用程序并逐步對其進行增強,從而了解所有這些方面的實際作用。 到本文結(jié)尾,您將具有在實際項目中開始實現(xiàn)這些概念的所有必要知識。
準備您的Rails應(yīng)用 (Preparing your Rails App)
So, as I already said, we are going to see all the concepts in action, therefore let’s create a new Rails application by running:
因此,正如我已經(jīng)說過的,我們將看到所有實際的概念,因此讓我們通過運行以下命令創(chuàng)建一個新的Rails應(yīng)用程序:
rails new SampleAppFor this tutorial I am using Rails 5.2.1, but most of the described concepts apply to older versions as well.
在本教程中,我使用的是Rails 5.2.1 ,但是大多數(shù)描述的概念也適用于舊版本。
Now let’s generate a StaticPagesController which is going to have an index action (our main page):
現(xiàn)在,讓我們生成一個StaticPagesController ,它將具有一個index動作(我們的主頁):
rails g controller StaticPages indexTweak the views/static_pages/index.html.erb view by adding some sample content:
通過添加一些示例內(nèi)容來調(diào)整views/static_pages/index.html.erb視圖:
<h1>Welcome!</h1> <p>We provide some fancy services to <em>good people</em>.</p>Also I would like to add a Feedback page where our users will be able to share their opinion (hopefully, a positive one) about the company. Each feedback will have an author’s name and the actual message:
另外,我想添加一個“反饋”頁面,我們的用戶可以在該頁面上分享他們對公司的看法(希望是正面的)。 每個反饋都將包含作者的姓名和實際信息:
rails g scaffold Feedback author messageWe will be interested only in two actions: new (which is going to render the form to post a review and also list all the existing reviews) and create (to actually validate and persist the reviews). Of course, ideally the reviews should be pre-moderated but we won’t bother with this today.
我們將只對以下兩項操作感興趣: new (將呈現(xiàn)表單以發(fā)布評論并列出所有現(xiàn)有評論)和create (實際驗證并保留評論)。 當(dāng)然,理想情況下,評論應(yīng)該是預(yù)先審核的,但今天我們不會理會。
Tweak the new action to fetch all the reviews from the database and order them by creation date:
調(diào)整new操作以從數(shù)據(jù)庫中獲取所有評論,并按創(chuàng)建日期對其進行排序:
# feedbacks_controller.rb # ... def new @feedback = Feedback.new @feedbacks = Feedback.order created_at: :desc endAlso I would like to redirect the user to the Feedback page when the form is processed and the new record is persisted:
另外,在處理表單并保留新記錄時,我想將用戶重定向到“反饋”頁面:
# feedbacks_controller.rb # ... def create @feedback = Feedback.new(feedback_params) if @feedback.save redirect_to new_feedback_path else @feedbacks = Feedback.order created_at: :desc render :new end endRender the feedbacks collection on the new page:
在new頁面上呈現(xiàn)反饋集合:
<!-- views/feedbacks/new.html.erb --> <!-- other code goes here... --> <%= render @feedbacks %>Lastly, create a partial for an individual feedback:
最后,為單個反饋創(chuàng)建部分內(nèi)容:
<!-- views/feedbacks/_feedback.html.erb --> <article> <em> <%= tag.time feedback.created_at, datetime: feedback.created_at %><br> Posted by <%= feedback.author %> </em> <p> <%= feedback.message %> </p> <hr> </article>Take care of the routes:
照顧路線:
# config/routes.rb Rails.application.routes.draw do resources :feedbacks root 'static_pages#index' endLastly add a global menu to the layout:
最后,向布局添加一個全局菜單:
<!-- views/layouts/application.html.erb --> <!-- other code goes here... --> <nav> <ul> <li><%= link_to 'Home', root_path %></li> <li><%= link_to 'Feedback', new_feedback_path %></li> </ul> </nav>Now run migrations and boot up the server:
現(xiàn)在運行遷移并啟動服務(wù)器:
rails db:migrate rails sNavigate to the http://locahost:3000 and make sure that everything is fine. Now that we have something to work with, let’s proceed to the main part and localize our application.
導(dǎo)航到http://locahost:3000并確保一切正常。 現(xiàn)在我們有了一些需要處理的東西,讓我們繼續(xù)主要部分并本地化我們的應(yīng)用程序。
一點配置 (A Bit of Configuration)
Before performing translations, we need to decide which languages will be supported. You can choose any, but I will stick with Russian and English, with the latter set as a default. Reflect this inside the config/application.rb file:
在執(zhí)行翻譯之前,我們需要確定將支持哪些語言。 您可以選擇任何一種,但我會堅持使用俄語和英語,而后者默認設(shè)置為英語。 在config/application.rb文件中反映出來:
# ... config.i18n.available_locales = [:en, :ru] config.i18n.default_locale = :enAlso hook up a rails-i18n gem that has locale data for different languages. For example, it has translated names of the months, pluralization rules, and other useful stuff.
還要掛接一個rails-i18n gem ,它具有不同語言的語言環(huán)境數(shù)據(jù)。 例如,它翻譯了月份的名稱,復(fù)數(shù)規(guī)則和其他有用的東西。
# Gemfile # ... gem 'rails-i18n'Just install this gem and you are good to go:
只需安裝此gem,您就可以進行以下操作:
bundle install存儲翻譯 (Storing Translations)
Now that everything is configured, let’s take care of the home page and translate the text there.
現(xiàn)在,所有內(nèi)容都已配置完畢,讓我們來照顧主頁并在那里翻譯文本。
The simplest way to do this is by utilizing localized views. All you need to do is create views named index.LANG_CODE.html.erb, where the LANG_CODE corresponds to one of the supported languages. So, in this demo we should created two views: index.en.html.erb and index.ru.html.erb. Inside just place content for English and Russian version of the site, and Rails will automatically pick the proper view based on the currently set locale. Convenient, eh?
最簡單的方法是利用本地化視圖 。 您需要做的就是創(chuàng)建名為index.LANG_CODE.html.erb視圖,其中LANG_CODE對應(yīng)于一種受支持的語言。 因此,在此演示中,我們應(yīng)該創(chuàng)建兩個視圖: index.en.html.erb和index.ru.html.erb 。 在僅放置英語和俄語版本站點內(nèi)容的地方,Rails會根據(jù)當(dāng)前設(shè)置的語言環(huán)境自動選擇正確的視圖。 方便嗎?
This approach, however, is not always feasible. Another way would be to store your translated strings in a separate file, and render a proper version of the string based on the chosen language. By default, Rails employs YAML files that has to be stored under the config/locales directory. Translations for different languages are stored in separate files, and each file is named after this language.
但是,這種方法并不總是可行的。 另一種方法是將翻譯后的字符串存儲在單獨的文件中,然后根據(jù)所選語言呈現(xiàn)適當(dāng)版本的字符串。 默認情況下,Rails使用YAML文件 ,該文件必須存儲在config/locales目錄下。 不同語言的翻譯存儲在單獨的文件中,每個文件都以此語言命名。
Open the config/locales folder and note that there is already an en.yml file inside which has some sample data:
打開config/locales文件夾,注意其中已經(jīng)有一個en.yml文件,其中包含一些示例數(shù)據(jù):
en: hello: "Hello world"So, en is a top-level key representing the language that these translations are for. Next, there is a nested key-value pair, where hello is the translation key, and Hello world is the actual translated string. Let’s replace this pair with the following content:
因此, en是表示這些翻譯所針對的語言的頂級關(guān)鍵字。 接下來,有一個嵌套的鍵/值對,其中hello是轉(zhuǎn)換鍵 ,而Hello world是實際的轉(zhuǎn)換字符串。 讓我們用以下內(nèi)容替換這對:
en: welcome: "Welcome!"This is just a welcoming message from our homepage. Now create a ru.yml file in the config/locales folder and provide translated welcoming message there as well:
這只是我們主頁上的歡迎消息。 現(xiàn)在在config/locales文件夾中創(chuàng)建一個ru.yml文件,并在那里提供翻譯好的歡迎消息:
ru: welcome: "Добро пожаловать!"We have just created translation for our first string, which is really great.
我們剛剛為第一個字符串創(chuàng)建了翻譯,這確實很棒。
執(zhí)行簡單翻譯 (Performing Simple Translations)
Now that we have populated the YAML files with some data, let’s see how to employ the translated strings in the views. Actually, it is as simple as utilizing the translate method which is aliased as t. This method has one required argument: the name of the translation key:
現(xiàn)在,我們已經(jīng)用一些數(shù)據(jù)填充了YAML文件,讓我們看看如何在視圖中使用轉(zhuǎn)換后的字符串。 實際上,這與使用別名為t的translate方法一樣簡單。 此方法有一個必需的參數(shù):轉(zhuǎn)換鍵的名稱:
<!-- views/static_pages/index.html.erb --> <h1><%= t 'welcome' %></h1>When the page is requested, Rails looks up the string that corresponds to the provided key, and renders it. If the requested translation cannot be found, Rails will just render the key on the screen (and turn it to a more human-readable form).
當(dāng)請求頁面時,Rails查找與提供的鍵相對應(yīng)的字符串,并將其呈現(xiàn)。 如果找不到所需的翻譯,Rails只會在屏幕上呈現(xiàn)鍵(并將其轉(zhuǎn)換為更易于理解的形式)。
Translation keys can be named anything you like (well, nearly anything) but of course it is advised to give them some meaningful names so that you can understand what text they correspond to.
可以將翻譯鍵命名為任何您喜歡的名稱(當(dāng)然,幾乎可以使用任何名稱),但是當(dāng)然建議給它們指定一些有意義的名稱,以便您可以理解它們對應(yīng)的文本。
Let’s take care of the second message:
讓我們處理第二條消息:
en: welcome: "Welcome!" services_html: "We provide some fancy services to <em>good people</em>."ru: welcome: "Добро пожаловать!" services_html: "Мы предоставляем различные услуги для <em>хороших людей</em>."Why do we need this _html postfix? Well, as you can see our string has some HTML markup, and by default Rails will render the em tag as plain text. As long as we don’t want this to happen, we mark the string as a “safe HTML”.
為什么我們需要這個_html后綴? 好了,正如您所看到的,我們的字符串具有一些HTML標記,默認情況下,Rails會將em標簽呈現(xiàn)為純文本。 只要我們不希望發(fā)生這種情況,我們就將該字符串標記為“安全HTML”。
Now just use the t method again:
現(xiàn)在,再次使用t方法:
<!-- views/static_pages/index.html.erb --> <!-- ... ---> <p><%= t 'services_html' %></p>有關(guān)翻譯鍵的更多信息 (More On Translation Keys)
Our homepage is now localized, but let’s stop for a moment and think about what we have done. All in all, our translation keys have meaningful names, but what happens if we are going to have, say, 500 messages in the app? This number is actually not that big, and large websites may have thousands of translations.
我們的主頁現(xiàn)在已經(jīng)本地化,但讓我們停一會兒,想一想我們做了什么。 總而言之,我們的翻譯鍵具有有意義的名稱,但是如果應(yīng)用程序中要有500條消息怎么辦? 這個數(shù)字實際上并不算大,大型網(wǎng)站可能有成千上萬的翻譯。
If all our key-values pairs are stored right under the en (or ru) key without any further grouping, this leads to two main problems:
如果我們所有的鍵值對都直接存儲在en (或ru )鍵下而沒有任何進一步的分組,則會導(dǎo)致兩個主要問題:
- We need to make sure that all the keys have unique names. This becomes increasingly complex as your application grows. 我們需要確保所有鍵都有唯一的名稱。 隨著應(yīng)用程序的增長,這變得越來越復(fù)雜。
- It is hard to locate all related translations (for example, translations for a single page or feature). 很難找到所有相關(guān)的翻譯(例如,單個頁面或功能的翻譯)。
Therefore, it would be a good idea to further group your translations under arbitrary keys. For example, you may do something like this:
因此,最好將您的翻譯進一步歸類到任意鍵下。 例如,您可以執(zhí)行以下操作:
en: main_page: header: welcome: "Welcoming message goes here"The level of nesting is not limited (but you should be reasonable about it), and the keys in different groups may have identical names.
嵌套級別不受限制(但是您應(yīng)該對此有所了解),并且不同組中的鍵名稱可能相同。
It is beneficial, however, to follow the folder structure of your views (in a moment we will see why). Therefore, tweak the YAML files in the following way:
但是,遵循視圖的文件夾結(jié)構(gòu)是有益的(稍后我們將了解原因)。 因此,以以下方式調(diào)整YAML文件:
en: static_pages: index: welcome: "Welcome!" services_html: "We provide some fancy services to <em>good people</em>."ru: static_pages: index: welcome: "Добро пожаловать!" services_html: "Мы предоставляем различные услуги для <em>хороших людей</em>."Generally, you need to provide full path to the translation key when referencing it in the t method:
通常,在t方法中引用轉(zhuǎn)換鍵時,需要提供完整的路徑:
<!-- views/static_pages/index.html.erb --> <h1><%= t 'static_pages.index.welcome' %></h1> <p><%= t 'static_pages.index.services_html' %></p>However, there is also a “l(fā)azy” lookup available. If you perform translation in a view or controller, and the translation keys are namespaced properly following the folder structure, you may omit the namespaces all together. This way, the above code turns to:
但是,也可以使用“惰性”查找。 如果您在視圖或控制器中執(zhí)行翻譯,并且翻譯鍵在文件夾結(jié)構(gòu)之后正確地命名,則可以一起忽略命名空間。 這樣,上面的代碼變?yōu)?#xff1a;
<!-- views/static_pages/index.html.erb --> <h1><%= t '.welcome' %></h1> <p><%= t '.services_html' %></p>Note that the leading dot is required here.
請注意,此處需要前導(dǎo)點。
Let’s also translate our global menu and namespace the translations properly:
我們還要正確翻譯全局菜單和名稱空間:
en: global: menu: home: "Home" feedback: "Feedback"ru: global: menu: home: "Главная" feedback: "Отзывы"In this case we can’t take advantage of the lazy lookup, so provide the full path:
在這種情況下,我們無法利用延遲查找,因此請?zhí)峁┩暾窂?#xff1a;
<!-- views/layouts/application.html.erb --> <!-- ... ---> <nav> <ul> <li><%= link_to t('global.menu.home'), root_path %></li> <li><%= link_to t('global.menu.feedback'), new_feedback_path %></li> </ul> </nav>翻譯模型 (Translating Models)
Now let’s proceed to the Feedback page and take care of the form. The first thing we need to translate is the labels for the inputs. It appears that Rails allows us to provide translations for the model attributes, and they will be automatically utilized as needed. All you need to do is namespace these translations properly:
現(xiàn)在,讓我們進入“反饋”頁面并處理表單。 我們需要翻譯的第一件事是輸入的標簽。 看起來,Rails允許我們?yōu)槟P蛯傩蕴峁┺D(zhuǎn)換,并且將根據(jù)需要自動使用它們。 您需要做的就是正確地命名這些翻譯的名稱空間:
en: activerecord: attributes: feedback: author: "Your name" message: "Message"ru: activerecord: attributes: feedback: author: "Ваше имя" message: "Сообщение"The labels will now be translated automatically. As for the “submit” button, you can provide translation for model itself by saying:
標簽現(xiàn)在將自動翻譯。 至于“提交”按鈕,您可以通過以下方式為模型本身提供翻譯:
en: activerecord: models: feedback: "Feedback"But honestly I don’t like the “Create Feedback” text on this button, so let’s stick with a generic “Submit” word:
但老實說,我不喜歡此按鈕上的“創(chuàng)建反饋”文本,所以讓我們堅持使用通用的“提交”一詞:
en: global: forms: submit: Submitru: global: forms: submit: ОтправитьNow utilize this translation:
現(xiàn)在利用此翻譯:
<!-- views/feedbacks/_form.html.erb --> <!-- ... ---> <%= form.submit t('global.forms.submit') %>錯誤訊息 (Error Messages)
Probably we do not want the visitors to post empty feedback messages, therefore provide some simple validation rules:
可能我們不希望訪問者發(fā)布空的反饋消息,因此提供一些簡單的驗證規(guī)則:
# models/feedback.rb # ... validates :author, presence: true validates :message, presence: true, length: {minimum: 5}But what about the corresponding error messages? How do we translate them? It appears that we don’t need to do anything at all as rails-i18n gem already knows how to localize common errors. For example, this file contains error messages for the Russian locale. If you actually do want to tweak the default error messages, then check the official doc that explains how to achieve that.
但是相應(yīng)的錯誤消息呢? 我們?nèi)绾畏g它們? 看起來我們根本不需要做任何事情,因為rails-i18n gem已經(jīng)知道如何定位常見錯誤。 例如, 此文件包含俄語語言環(huán)境的錯誤消息。 如果你其實想調(diào)整默認的錯誤信息,然后檢查的官方文檔 ,介紹如何實現(xiàn)這一點。
One problem with the form, however, is that the error messages subtitle (the one that says “N errors prohibited this feedback from being saved:”) is not translated. Let’s fix it now and also talk about pluralization.
但是,該格式存在一個問題,即錯誤消息字幕(顯示“ N個錯誤禁止保存此反饋:”的錯誤消息)的字幕未翻譯。 現(xiàn)在修復(fù)它,并討論多元性。
復(fù)數(shù)規(guī)則 (Pluralization Rules)
As long as potentially there can be one or more error messages, the “error” word in the subtitle should be pluralized accordingly. In English words are usually pluralized by adding an “s” postfix, but for Russian the rules are a bit more complex.
只要可能存在一個或多個錯誤消息,字幕中的“錯誤”一詞就應(yīng)相應(yīng)地復(fù)數(shù)。 英文單詞通常通過添加“ s”后綴來復(fù)數(shù)形式,但是對于俄語而言,規(guī)則要復(fù)雜一些。
I already mentioned that the rails-i18n gem contains pluralization rules for all the supported languages, so we don’t need to bother writing them from scratch. All you need to do is provide the proper key for each possible case. So, for English there are only two possible cases: one error or many errors (of course, there can be no errors, but in this case the message won’t be displayed at all).
我已經(jīng)提到過,rails-i18n gem包含所有受支持語言的復(fù)數(shù)規(guī)則,因此我們無需從頭開始編寫它們。 您需要做的就是為每種可能的情況提供正確的密鑰。 因此,對于英語,只有兩種可能的情況:一個錯誤或許多錯誤(當(dāng)然,不會有錯誤,但是在這種情況下,該消息將根本不會顯示)。
en: global: forms: submit: Submit messages: errors: one: "One error prohibited this feedback from being saved" other: "%{count} errors prohibited this feedback from being saved"The %{count} here is interpolation – we take the passed value and place it right into the string.
這里的%{count}是插值–我們將傳遞的值放入字符串中。
Now take care of the Russian locale which has more possible cases:
現(xiàn)在,請注意具有更多可能情況的俄語語言環(huán)境:
ru: global: forms: submit: Отправить messages: errors: one: "Не удалось сохранить отзыв! Найдена одна ошибка:" few: "Не удалось сохранить отзыв! Найдены %{count} ошибки:" many: "Не удалось сохранить отзыв! Найдено %{count} ошибок:" other: "Не удалось сохранить отзыв! Найдена %{count} ошибка:"Having this in place, just utilize these translation:
準備好這些后,只需利用以下翻譯即可:
<!-- views/feedbacks/_form.html.erb --> <!-- ... ---> <%= form_with(model: feedback, local: true) do |form| %> <% if feedback.errors.any? %> <div id="error_explanation"> <h2><%= t 'global.forms.messages.errors', count: feedback.errors.count %></h2> <!-- errors... --> </ul> </div> <% end %> <!-- form fields --> <% end %>Note that in this case we pass the translation key as well as the value for the count variable. Rails will take the proper translation variant based on this number. Also the value of the count will be interpolated into each %{count} placeholder.
請注意,在這種情況下,我們傳遞轉(zhuǎn)換鍵以及count變量的值。 Rails將根據(jù)此數(shù)字采用適當(dāng)?shù)姆g變體。 同樣, count將被插入到每個%{count}占位符中。
Our next stop is the _feedback.html.erb partial. Here we need to localize two strings: “Posted by…” and datetime (created_at field). As for “Posted by…”, let’s just utilize the interpolation again:
我們的下一站是_feedback.html.erb部分。 在這里,我們需要本地化兩個字符串:“ Posted by…”和datetime( created_at字段)。 至于“ Posted by…”,讓我們再次利用插值:
en: global: feedback: posted_by: "Posted by %{author}"ru: global: feedback: posted_by: "Автор: %{author}"<!-- views/feedbacks/_feedback.html.erb --> <article> <em> <%= tag.time feedback.created_at, datetime: feedback.created_at %><br> <%= t 'global.feedback.posted_by', author: feedback.author %> </em> <p> <%= feedback.message %> </p> <hr> </article>But what about the created_at? To take care of it, we can take advantage of the localize method aliased as just l. It is very similar to the Ruby’s strftime, but produces a translated version of the date (specifically, the months’ names are translated properly). Let’s use a predefined format called :long:
但是created_at呢? 為了解決這個問題,我們可以利用別名l的localize方法。 它與Ruby的strftime非常相似,但是會生成日期的翻譯版本(特別是月份的名稱已正確翻譯)。 讓我們使用一種稱為:long的預(yù)定義格式 :
<!-- views/feedbacks/_feedback.html.erb --> <article> <em> <%= tag.time l(feedback.created_at, format: :long), datetime: feedback.created_at %><br> <%= t 'global.feedback.posted_by', author: feedback.author %> </em> <!--... --> </article>If you would like to add your very own format, it is possible too as explained here.
如果您想添加自己的格式,也可以按照此處的說明進行 。
在語言環(huán)境之間切換 (Switching Between Locales)
So, our app is now fully translated… but there is a very minor thing: we cannot change the locale! Come to think of it, this is quite a major issue really, so let’s fix it now.
因此,我們的應(yīng)用程序現(xiàn)已完全翻譯……但是有一件非常小的事情:我們無法更改語言環(huán)境! 考慮一下,這確實是一個重大問題,所以現(xiàn)在就修復(fù)它。
There are a handful of possible ways of setting and persisting the chosen locale across the requests. We are going to stick with the following approach:
在請求中有幾種設(shè)置和保留所選語言環(huán)境的可能方法 。 我們將堅持以下方法:
Our URLs will have an optional :locale parameter, and so they’ll look like http://localhost:3000/en/some_page
我們的URL將具有可選的:locale參數(shù),因此它們看起來像http://localhost:3000/en/some_page
- If this parameter is set and the specified locale is supported, we translate the app into the corresponding language 如果設(shè)置了此參數(shù)并且支持指定的語言環(huán)境,我們會將應(yīng)用翻譯成相應(yīng)的語言
- If this parameter is not set or the locale is not supported, set a default locale 如果未設(shè)置此參數(shù)或不支持語言環(huán)境,請設(shè)置默認語言環(huán)境
Sounds straightforward? Then let’s dive into the code!
聽起來很簡單? 然后,讓我們深入研究代碼!
First of all, tweak the routes.rb by including a scope:
首先,通過包含一個scope調(diào)整routes.rb :
# config/routes.rb scope "(:locale)", locale: /#{I18n.available_locales.join("|")}/ do # your routes here... endHere we are validating the specified parameter using a RegEx to make sure that the locale is supported (note that the anchor characters like \A are not permitted here).
在這里,我們使用RegEx驗證指定的參數(shù),以確保支持語言環(huán)境(請注意,此處不允許使用\A類的錨字符)。
Next, set a before_action in the ApplicationController to check and set the locale on each request:
接下來,在ApplicationController設(shè)置一個before_action來檢查和設(shè)置每個請求的語言環(huán)境:
# application_controller.rb # ... before_action :set_locale private def set_locale I18n.locale = extract_locale || I18n.default_locale end def extract_locale parsed_locale = params[:locale] I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil endAlso, in order to persist the chosen locale across the requests, set the default_url_options:
另外,為了在請求中保留選定的語言環(huán)境,請設(shè)置default_url_options :
# application_controller.rb # ... private def default_url_options { locale: I18n.locale } endThe is going to include the locale parameter into every link generated with Rails helpers.
它將在每個Rails助手生成的鏈接中包括locale參數(shù)。
The last step is to present two links to switch between locales:
最后一步是提供兩個鏈接以在語言環(huán)境之間切換:
<!-- views/layouts/application.html.erb --> <!-- ... --> <nav> <ul> <li><%= link_to t('global.menu.home'), root_path %></li> <li><%= link_to t('global.menu.feedback'), new_feedback_path %></li> </ul> <ul> <li><%= link_to 'English', root_path(locale: :en) %></li> <li><%= link_to 'Русский', root_path(locale: :ru) %></li> </ul> </nav>As an exercise, you may make these links more fancy and, for instance, redirect the user back to the page that he was browsing.
作為練習(xí),您可以使這些鏈接更加精美,例如,將用戶重定向回他正在瀏覽的頁面。
通過Lokalise簡化生活 (Simplify Your Life With Lokalise)
By now you are probably thinking that supporting multiple languages on a big website is probably a pain. And, honestly, you are right. Of course, the translations can be namespaced, and even split into multiple YAML files if needed, but still you must make sure that all the keys are translated for each and every locale.
到現(xiàn)在為止,您可能會認為在一個大型網(wǎng)站上支持多種語言可能很痛苦。 而且,老實說,你是對的。 當(dāng)然,翻譯可以命名空間,如果需要的話甚至可以拆分成多個YAML文件 ,但是仍然必須確保為每個語言環(huán)境翻譯了所有鍵。
Luckily, there is a solution to this problem: the Lokalise platform that makes working with the localization files much simpler. Let me guide you through the initial setup which is nothing complex really.
幸運的是,有一個解決此問題的方法:使用Lokalise平臺可以更輕松地處理本地化文件 。 讓我指導(dǎo)您完成初始設(shè)置,這實際上并不復(fù)雜。
To get started, grab your free trial
首先, 請免費試用
Install Lokalise CLI that will be used to upload and download translation files
安裝Lokalise CLI ,它將用于上載和下載翻譯文件
Open your personal profile page, navigate to the “API tokens” section, and generate a read/write token
打開您的個人資料頁面 ,導(dǎo)航到“ API令牌”部分,并生成一個讀/寫令牌
- Create a new project, give it some name, and set English as a base language 創(chuàng)建一個新項目,為其命名,并將英語設(shè)置為基本語言
- On the project page click the “More” button and choose “Settings”. On this page you should see the project ID 在項目頁面上,單擊“更多”按鈕,然后選擇“設(shè)置”。 在此頁面上,您應(yīng)該看到項目ID
Now from the command line simply run lokalise --token <token> import <project_id> --lang_iso en --file config/locales/en.yml while providing your generated token and project ID (on Windows you may also need to provide the full path to the file). This should upload English translation to Lokalise. Run the same command for the Russian locale.
現(xiàn)在從命令行中只需運行l(wèi)okalise --token <token> import <project_id> --lang_iso en --file config/lo cales / en.yml,同時提供生成的令牌和項目ID(在Windows上,您可能還需要提供文件的完整路徑)。 這應(yīng)該將英語翻譯上傳到Lokalise。 在俄語語言環(huán)境中運行相同的命令。
- Navigate back to the project overview page. You should see all your translation keys and values there. Of course, it is possible to edit, delete them, as well as add new ones. Here you may also filter the keys and, for example, find the untraslated ones which is really convenient. 導(dǎo)航回到項目概述頁面。 您應(yīng)該在那里看到所有翻譯鍵和值。 當(dāng)然,可以編輯,刪除它們以及添加新的。 在這里您還可以過濾鍵,例如,找到未翻譯的鍵,這確實很方便。
After you are done editing the translations, download them back by running lokalise --token <token> export <project_id> --type yaml --bundle_structure %LANG_ISO%.yml --unzip_to E:/Supreme/docs/work/lokalise/rails/SampleApp/config/locales/. Great!
編輯完翻譯后,請運行l(wèi)okalise --token <token> export <project_id> --type yaml --bundle_structure %LANG_ISO%.yml --unzip_to E:/Supreme/docs/work/lokalise/rails/SampleApp/con將其下載回lokalise --token <token> export <project_id> --type yaml --bundle_structure %LANG_ISO%.yml --unzip_to E:/Supreme/docs/work/lokalise/rails/SampleApp/con fig / locales /。 大!
Lokalise has many more features including support for dozens of platforms and formats, ability to order translations from professionals, and even the possibility to upload screenshots in order to read texts from them. So, stick with Lokalise and make your life easier!
Lokalise具有更多功能,包括對多種平臺和格式的支持,從專業(yè)人員處訂購翻譯的能力,甚至可以上傳屏幕截圖以從中讀取文本。 因此,堅持使用Lokalise,讓您的生活更輕松!
結(jié)論 (Conclusion)
In this article we have thoroughly discussed how to introduce internationalization support in Rails applications and implemented it ourselves. You have learned how and where to store translations, how to look them up, what are localized views, how to translate error messages and ActiveRecord-related stuff, as well as how to switch between locales and persist the chosen locale among the request. Not bad for today, eh?
在本文中,我們徹底討論了如何在Rails應(yīng)用程序中引入國際化支持并自己實現(xiàn)。 您已經(jīng)了解了如何以及在何處存儲翻譯,如何查找它們,什么是本地化視圖,如何翻譯錯誤消息和與ActiveRecord相關(guān)的內(nèi)容,以及如何在語言環(huán)境之間切換以及在請求中保留所選語言環(huán)境。 今天還不錯吧?
Of course, it is impossible to cover all ins and outs of Rails I18n in one article, and so I recommend checking out the official guide that gives some more detailed information on the topic and provides useful examples.
當(dāng)然,不可能在一篇文章中涵蓋Rails I18n的所有內(nèi)容,因此,我建議您查閱官方指南 , 該指南提供了有關(guān)該主題的更多詳細信息并提供了有用的示例。
Originally published at blog.lokalise.co on August 23, 2018.
最初于2018年8月23日發(fā)布在blog.lokalise.co 。
翻譯自: https://www.freecodecamp.org/news/lokalise-co-blog-bf840492f34f/
rails i18n模型
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的rails i18n模型_Rails国际化的完整指南(i18n)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到自己受枪伤什么意思
- 下一篇: 梦到家里花开了是怎么回事