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.

在本文中,您将学习如何将Rails应用程序翻译成多种语言,使用翻译,本地化日期时间以及切换语言环境。 我们将通过创建示例应用程序并逐步对其进行增强,从而了解所有这些方面的实际作用。 到本文结尾,您将具有在实际项目中开始实现这些概念的所有必要知识。

准备您的Rails应用 (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:

因此,正如我已经说过的,我们将看到所有实际的概念,因此让我们通过运行以下命令创建一个新的Rails应用程序:

rails new SampleApp

For 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 ,但是大多数描述的概念也适用于旧版本。

Now let’s generate a StaticPagesController which is going to have an index action (our main page):

现在,让我们生成一个StaticPagesController ,它将具有一个index动作(我们的主页):

rails g controller StaticPages index

Tweak the views/static_pages/index.html.erb view by adding some sample content:

通过添加一些示例内容来调整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 message

We 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 (将呈现表单以发布评论并列出所有现有评论)和create (实际验证并保留评论)。 当然,理想情况下,评论应该是预先审核的,但今天我们不会理会。

Tweak the new action to fetch all the reviews from the database and order them by creation date:

调整new操作以从数据库中获取所有评论,并按创建日期对其进行排序:

# feedbacks_controller.rb # ... def new @feedback = Feedback.new @feedbacks = Feedback.order created_at: :desc end

Also 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 end

Render the feedbacks collection on the new page:

new页面上呈现反馈集合:

<!-- views/feedbacks/new.html.erb --> <!-- other code goes here... --> <%= render @feedbacks %>

Lastly, create a partial for an individual feedback:

最后,为单个反馈创建部分内容:

<!-- 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' end

Lastly 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:

现在运行迁移并启动服务器:

rails db:migrate rails s

Navigate 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.

导航到http://locahost:3000并确保一切正常。 现在我们有了一些需要处理的东西,让我们继续主要部分并本地化我们的应用程序。

一点配置 (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:

在执行翻译之前,我们需要确定将支持哪些语言。 您可以选择任何一种,但我会坚持使用俄语和英语,而后者默认设置为英语。 在config/application.rb文件中反映出来:

# ... config.i18n.available_locales = [:en, :ru] config.i18n.default_locale = :en

Also 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 ,它具有不同语言的语言环境数据。 例如,它翻译了月份的名称,复数规则和其他有用的东西。

# 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.

现在,所有内容都已配置完毕,让我们来照顾主页并在那里翻译文本。

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?

最简单的方法是利用本地化视图 。 您需要做的就是创建名为index.LANG_CODE.html.erb视图,其中LANG_CODE对应于一种受支持的语言。 因此,在此演示中,我们应该创建两个视图: index.en.html.erbindex.ru.html.erb 。 在仅放置英语和俄语版本站点内容的地方,Rails会根据当前设置的语言环境自动选择正确的视图。 方便吗?

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.

但是,这种方法并不总是可行的。 另一种方法是将翻译后的字符串存储在单独的文件中,然后根据所选语言呈现适当版本的字符串。 默认情况下,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文件夹,注意其中已经有一个en.yml文件,其中包含一些示例数据:

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是表示这些翻译所针对的语言的顶级关键字。 接下来,有一个嵌套的键/值对,其中hello转换键 ,而Hello world是实际的转换字符串。 让我们用以下内容替换这对:

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:

这只是我们主页上的欢迎消息。 现在在config/locales文件夹中创建一个ru.yml文件,并在那里提供翻译好的欢迎消息:

ru: welcome: "Добро пожаловать!"

We have just created translation for our first string, which is really great.

我们刚刚为第一个字符串创建了翻译,这确实很棒。

执行简单翻译 (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:

现在,我们已经用一些数据填充了YAML文件,让我们看看如何在视图中使用转换后的字符串。 实际上,这与使用别名为ttranslate方法一样简单。 此方法有一个必需的参数:转换键的名称:

<!-- 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).

当请求页面时,Rails查找与提供的键相对应的字符串,并将其呈现。 如果找不到所需的翻译,Rails只会在屏幕上呈现键(并将其转换为更易于理解的形式)。

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.

可以将翻译键命名为任何您喜欢的名称(当然,几乎可以使用任何名称),但是当然建议给它们指定一些有意义的名称,以便您可以理解它们对应的文本。

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标签呈现为纯文本。 只要我们不希望发生这种情况,我们就将该字符串标记为“安全HTML”。

Now just use the t method again:

现在,再次使用t方法:

<!-- views/static_pages/index.html.erb --> <!-- ... ---> <p><%= t 'services_html' %></p>

有关翻译键的更多信息 (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.

我们的主页现在已经本地化,但让我们停一会儿,想一想我们做了什么。 总而言之,我们的翻译键具有有意义的名称,但是如果应用程序中要有500条消息怎么办? 这个数字实际上并不算大,大型网站可能有成千上万的翻译。

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 )键下而没有任何进一步的分组,则会导致两个主要问题:

  • We need to make sure that all the keys have unique names. This becomes increasingly complex as your application grows.

    我们需要确保所有键都有唯一的名称。 随着应用程序的增长,这变得越来越复杂。
  • It is hard to locate all related translations (for example, translations for a single page or feature).

    很难找到所有相关的翻译(例如,单个页面或功能的翻译)。

Therefore, it would be a good idea to further group your translations under arbitrary keys. For example, you may do something like this:

因此,最好将您的翻译进一步归类到任意键下。 例如,您可以执行以下操作:

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.

嵌套级别不受限制(但是您应该对此有所了解),并且不同组中的键名称可能相同。

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:

但是,遵循视图的文件夹结构是有益的(稍后我们将了解原因)。 因此,以以下方式调整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方法中引用转换键时,需要提供完整的路径:

<!-- 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 “lazy” 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:

但是,也可以使用“惰性”查找。 如果您在视图或控制器中执行翻译,并且翻译键在文件夹结构之后正确地命名,则可以一起忽略命名空间。 这样,上面的代码变为:

<!-- views/static_pages/index.html.erb --> <h1><%= t '.welcome' %></h1> <p><%= t '.services_html' %></p>

Note that the leading dot is required here.

请注意,此处需要前导点。

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:

在这种情况下,我们无法利用延迟查找,因此请提供完整路径:

<!-- 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:

现在,让我们进入“反馈”页面并处理表单。 我们需要翻译的第一件事是输入的标签。 看起来,Rails允许我们为模型属性提供转换,并且将根据需要自动使用它们。 您需要做的就是正确地命名这些翻译的名称空间:

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:

标签现在将自动翻译。 至于“提交”按钮,您可以通过以下方式为模型本身提供翻译:

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:

但老实说,我不喜欢此按钮上的“创建反馈”文本,所以让我们坚持使用通用的“提交”一词:

en: global: forms: submit: Submit
ru: global: forms: submit: Отправить

Now utilize this translation:

现在利用此翻译:

<!-- 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:

可能我们不希望访问者发布空的反馈消息,因此提供一些简单的验证规则:

# 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.

但是相应的错误消息呢? 我们如何翻译它们? 看起来我们根本不需要做任何事情,因为rails-i18n gem已经知道如何定位常见错误。 例如, 此文件包含俄语语言环境的错误消息。 如果其实想调整默认的错误信息,然后检查的官方文档 ,介绍如何实现这一点。

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个错误禁止保存此反馈:”的错误消息)的字幕未翻译。 现在修复它,并讨论多元性。

复数规则 (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.

只要可能存在一个或多个错误消息,字幕中的“错误”一词就应相应地复数。 英文单词通常通过添加“ s”后缀来复数形式,但是对于俄语而言,规则要复杂一些。

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).

我已经提到过,rails-i18n gem包含所有受支持语言的复数规则,因此我们无需从头开始编写它们。 您需要做的就是为每种可能的情况提供正确的密钥。 因此,对于英语,只有两种可能的情况:一个错误或许多错误(当然,不会有错误,但是在这种情况下,该消息将根本不会显示)。

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:

现在,请注意具有更多可能情况的俄语语言环境:

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.

请注意,在这种情况下,我们传递转换键以及count变量的值。 Rails将根据此数字采用适当的翻译变体。 同样, 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呢? 为了解决这个问题,我们可以利用别名llocalize方法。 它与Ruby的strftime非常相似,但是会生成日期的翻译版本(特别是月份的名称已正确翻译)。 让我们使用一种称为:long预定义格式

<!-- 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.

如果您想添加自己的格式,也可以按照此处的说明进行

在语言环境之间切换 (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.

因此,我们的应用程序现已完全翻译……但是有一件非常小的事情:我们无法更改语言环境! 考虑一下,这确实是一个重大问题,所以现在就修复它。

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:

在请求中有几种设置和保留所选语言环境的可能方法 。 我们将坚持以下方法:

  • Our URLs will have an optional :locale parameter, and so they’ll look like http://localhost:3000/en/some_page

    我们的URL将具有可选的:locale参数,因此它们看起来像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

    如果设置了此参数并且支持指定的语言环境,我们会将应用翻译成相应的语言
  • If this parameter is not set or the locale is not supported, set a default locale

    如果未设置此参数或不支持语言环境,请设置默认语言环境

Sounds straightforward? Then let’s dive into the code!

听起来很简单? 然后,让我们深入研究代码!

First of all, tweak the routes.rb by including a scope:

首先,通过包含一个scope调整routes.rb

# config/routes.rb scope "(:locale)", locale: /#{I18n.available_locales.join("|")}/ do # your routes here... end

Here 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验证指定的参数,以确保支持语言环境(请注意,此处不允许使用\A类的锚字符)。

Next, set a before_action in the ApplicationController to check and set the locale on each request:

接下来,在ApplicationController设置一个before_action来检查和设置每个请求的语言环境:

# 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 end

Also, in order to persist the chosen locale across the requests, set the default_url_options:

另外,为了在请求中保留选定的语言环境,请设置default_url_options

# application_controller.rb # ... private def default_url_options { locale: I18n.locale } end

The is going to include the locale parameter into every link generated with Rails helpers.

它将在每个Rails助手生成的链接中包括locale参数。

The last step is to present two links to switch between locales:

最后一步是提供两个链接以在语言环境之间切换:

<!-- 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.

作为练习,您可以使这些链接更加精美,例如,将用户重定向回他正在浏览的页面。

通过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.

到现在为止,您可能会认为在一个大型网站上支持多种语言可能很痛苦。 而且,老实说,你是对的。 当然,翻译可以命名空间,如果需要的话甚至可以拆分成多个YAML文件 ,但是仍然必须确保为每个语言环境翻译了所有键。

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平台可以更轻松地处理本地化文件 。 让我指导您完成初始设置,这实际上并不复杂。

  • 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

    打开您的个人资料页面 ,导航到“ API令牌”部分,并生成一个读/写令牌

  • Create a new project, give it some name, and set English as a base language

    创建一个新项目,为其命名,并将英语设置为基本语言
  • On the project page click the “More” button and choose “Settings”. On this page you should see the project ID

    在项目页面上,单击“更多”按钮,然后选择“设置”。 在此页面上,您应该看到项目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.

    现在从命令行中只需运行lokalise --token <token> import <project_id> --lang_iso en --file config/lo cales / en.yml,同时提供生成的令牌和项目ID(在Windows上,您可能还需要提供文件的完整路径)。 这应该将英语翻译上传到Lokalise。 在俄语语言环境中运行相同的命令。

  • 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.

    导航回到项目概述页面。 您应该在那里看到所有翻译键和值。 当然,可以编辑,删除它们以及添加新的。 在这里您还可以过滤键,例如,找到未翻译的键,这确实很方便。
  • 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!

    编辑完翻译后,请运行lokalise --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具有更多功能,包括对多种平台和格式的支持,从专业人员处订购翻译的能力,甚至可以上传屏幕截图以从中读取文本。 因此,坚持使用Lokalise,让您的生活更轻松!

结论 (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应用程序中引入国际化支持并自己实现。 您已经了解了如何以及在何处存储翻译,如何查找它们,什么是本地化视图,如何翻译错误消息和与ActiveRecord相关的内容,以及如何在语言环境之间切换以及在请求中保留所选语言环境。 今天还不错吧?

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.

当然,不可能在一篇文章中涵盖Rails I18n的所有内容,因此,我建议您查阅官方指南该指南提供了有关该主题的更多详细信息并提供了有用的示例。

Originally published at blog.lokalise.co on August 23, 2018.

最初于2018年8月23日发布在blog.lokalise.co

翻译自: https://www.freecodecamp.org/news/lokalise-co-blog-bf840492f34f/

rails i18n模型

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值