angular i18n_如何使用i18n工具在Angular中实现本地化

angular i18n

介绍 (Introduction)

In this article, we will learn how to make our Angular app available in different languages using i18n and localization. We will create an Angular application and configure it to serve the content in three different languages. We will also deploy our app to Google Firebase and see how localization works in real time.

在本文中,我们将学习如何使用i18n和本地化以不同的语言提供Angular应用程序。 我们将创建一个Angular应用程序,并将其配置为以三种不同的语言提供内容。 我们还将将应用程序部署到Google Firebase,并实时了解本地化的工作方式。

We will use Angular 7 and VS Code to develop our application. Take a look at the application output.

我们将使用Angular 7和VS Code开发我们的应用程序。 看一下应用程序输出。

源代码 (Source Code)

Get the source code for this application from GitHub.

GitHub获取此应用程序的源代码。

什么是i18n? (What is i18n?)

I18n , also known as internationalization, is the process of making our app support various languages to extend the reach to a worldwide audience.

I18n ,也称为国际化,是使我们的应用程序支持多种语言以将覆盖范围扩大到全球受众的过程。

什么是本地化? (What is Localization?)

Localization is the process for translating the app to a particular language. We need to apply internationalization to the application and after that we can localize it. Localization allows us to serve our application in different languages.

本地化是将应用翻译成特定语言的过程。 我们需要对应用程序应用国际化,然后我们可以对其进行本地化。 本地化使我们可以用不同的语言来服务我们的应用程序。

创建一个Angular 7应用 (Creating an Angular 7 app)

The first step is to create an Angular 7 app. If you are new to Angular, I would suggest you to read my article Getting Started With Angular 7.0 to learn how to set up Angular development environment in your machine.

第一步是创建一个Angular 7应用程序。 如果您不熟悉Angular,建议您阅读我的文章Angular 7.0入门,以了解如何在计算机中设置Angular开发环境。

Run the following command to create the app.

运行以下命令以创建应用程序。

ng new i18nDemo

Open the i18nDemo app using VS code.

使用VS代码打开i18nDemo应用。

设置应用程序组件 (Setting up the app component)

Open app.component.html file. Replace the already existing text with the following code.

打开app.component.html文件。 用以下代码替换现有的文本。

<h1 i18n>  Localization Demo in Angular using i18n</h1><h3 i18n="@@myName">  Hello, My name is Ankit</h3><p>This text will remain same in all languages</p><hr />

You can observe that we have marked <h1>; and <h3> tags with i18n attribute. This is a way to tell the Angular to consider this text as translatable content. We will explore i18n attribute in detail in the next section.

您可以看到我们已经标记了< h1> ; an 具有i18n属性; an d <h3>标签。 这是一种告诉Angular将此文本视为可翻译内容的方法。 我们将在下一节中详细探讨i18n属性。

创建翻译源文件 (Creating a translation source file)

Run the following command in the CLI to create a translation source file.

在CLI中运行以下命令以创建翻译源文件。

ng xi18n --output-path translate

It will create a folder called translate and create a messages.xlf file inside it. Open the file and you can observe the following XML code inside it.

它将创建一个名为translate的文件夹,并在其中创建一个messages.xlf文件。 打开文件,您可以观察其中的以下XML代码。

<?xml version="1.0" encoding="UTF-8" ?><xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">  <file source-language="en" datatype="plaintext" original="ng2.template">    <body>      <trans-unit id="3f2feb6d5fb690628177afa3ade2519db69ba838" datatype="html">        <source>Localization Demo in Angular using i18n</source>        <context-group purpose="location">          <context context-type="sourcefile">app/app.component.html</context>          <context context-type="linenumber">1</context>        </context-group>      </trans-unit>      <trans-unit id="myName" datatype="html">        <source>Hello, My name is Ankit</source>        <context-group purpose="location">          <context context-type="sourcefile">app/app.component.html</context>          <context context-type="linenumber">5</context>        </context-group>      </trans-unit>    </body>  </file></xliff>

This file contains a list of <trans-unit> tags. These tags will have all the content that was marked for translation using i18n attribute. You can also observe that each <trans-unit> tag has an id property associated with it. This unique id will be generated by default for each tag that was marked with i18n attribute. We can also customize the id by providing a name prefixed with @@ as we have done with <h3> tag in previous section. Hence, the id for <h3> tag is “myName” as we defined it.

该文件包含<trans-un it>标签的列表。 这些标签将包含所有使用i18n属性标记为要翻译的内容。 您还可以观察到each <tr ans-unit>标签都有一个与之关联的id属性。 默认情况下,将为每个标记有i18n属性的标签生成唯一的ID。 我们还可以通过提供的名称自定义ID PR ef ixed与@@因为我们甲肝e do NE与<H3>在前面的章节标记。 Henc E,id为<H3>标记是因为我们定义为“MYNAME”。

There is no entry for the <;p> tag in translation file because we have not marked it with i18n attribute. Angular translation tool will not consider it for translations.

翻译文件中的< ; p>标记没有任何条目,因为我们尚未使用i18n属性对其进行标记。 角度翻译工具不会考虑将其用于翻译。

If you change the text for any tag in your HTML file, you need to regenerate the translation file. Regenerating the file will override the default id of <trans-unit> tags. Hence, it is advisable to provide custom ids to each translatable tag to maintain consistency.

如果您更改HTML文件中任何标签的文本,则需要重新生成翻译文件。 重新生成文件将覆盖<trans-un it>标记的默认ID。 因此,建议为每个可翻译标签提供自定义ID,以保持一致性。

Hence, we have successfully implemented i18n to our app. In the next section, we will extend it to make it available to different languages.

因此,我们已成功将i18n实施到我们的应用程序中。 在下一节中,我们将扩展它以使其适用于不同的语言。

翻译内容 (Translating the content)

We will translate our application into two new languages apart from English, which are Spanish and Hindi. Make three copies of the messages.xlf file and rename them to messages.en.xlf, messages.es.xlf and messages.hi.xlf. These file names can be customized as per your choice, but the extension should be .xlf.

我们将把应用程序翻译成除英语之外的两种新语言,即西班牙语和北印度语。 制作messages.xlf文件的三个副本,然后将它们重命名为messages.en.xlfmessages.es.xlfmessages.hi.xlf 。 这些文件名可以根据您的选择进行自定义,但扩展名应为.xlf

Open messages.es.xlf and put in the following content in it.

打开messages.es.xlf,并在其中添加以下内容。

<?xml version="1.0" encoding="UTF-8" ?><xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">  <file source-language="en" datatype="plaintext" original="ng2.template">    <body>      <trans-unit id="3f2feb6d5fb690628177afa3ade2519db69ba838" datatype="html">        <source>Localization Demo in Angular using i18n</source>        <target>Demostración de localización en angular usando i18n</target>        <context-group purpose="location">          <context context-type="sourcefile">app/app.component.html</context>          <context context-type="linenumber">1</context>        </context-group>      </trans-unit>      <trans-unit id="myName" datatype="html">        <source>Hello, My name is Ankit</source>        <target>Hola, mi nombre es Ankit</target>        <context-group purpose="location">          <context context-type="sourcefile">app/app.component.html</context>          <context context-type="linenumber">5</context>        </context-group>      </trans-unit>    </body>  </file></xliff>

This is the same content as the original messages.xlf file, but we have added a <target> tag corresponding to each &lt;source&gt; tag. The <target> tag contains the translated text for the content inside the <source> tag. Here I am using Google translate for the translation, but in real time applications, a language expert will translate the contents from messages.xlf file.

这与原始messages.xlf文件的内容相同,但是我们添加了与each &l t; source&g t; tag.对应的<targ et>标记t; tag. t; tag. 在<目标>标记包含为C的翻译后的文本ontent i n侧的<源>标记。 在这里,我用谷歌翻译的翻译,但在实时应用,语言专家将陈德良slate the co从messages.xlf文件ntents。

Similarly, open the messages.hi.xlf and put in the following content in it.

同样,打开messages.hi.xlf并在其中添加以下内容。

<?xml version="1.0" encoding="UTF-8" ?><xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">  <file source-language="en" datatype="plaintext" original="ng2.template">    <body>      <trans-unit id="3f2feb6d5fb690628177afa3ade2519db69ba838" datatype="html">        <source>Localization Demo in Angular using i18n</source>        <target>I18n का उपयोग कर कोणीय में स्थानीयकरण डेमो</target>        <context-group purpose="location">          <context context-type="sourcefile">app/app.component.html</context>          <context context-type="linenumber">1</context>        </context-group>      </trans-unit>      <trans-unit id="myName" datatype="html">        <source>Hello, My name is Ankit</source>        <target>हेलो, मेरा नाम अंकित है</target>        <context-group purpose="location">          <context context-type="sourcefile">app/app.component.html</context>          <context context-type="linenumber">5</context>        </context-group>      </trans-unit>    </body>  </file></xliff>

Finally, we will make the English translation file. Open messages.en.xlf and put in the following content in it.

最后,我们将制作英语翻译文件。 打开messages.en.xlf,并在其中添加以下内容。

<?xml version="1.0" encoding="UTF-8" ?><xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">  <file source-language="en" datatype="plaintext" original="ng2.template">    <body>      <trans-unit id="3f2feb6d5fb690628177afa3ade2519db69ba838" datatype="html">        <source>Localization Demo in Angular using i18n</source>        <target>Localization Demo in Angular using i18n</target>        <context-group purpose="location">          <context context-type="sourcefile">app/app.component.html</context>          <context context-type="linenumber">1</context>        </context-group>      </trans-unit>      <trans-unit id="myName" datatype="html">        <source>Hello, My name is Ankit</source>        <target>Hello, My name is Ankit</target>        <context-group purpose="location">          <context context-type="sourcefile">app/app.component.html</context>          <context context-type="linenumber">5</context>        </context-group>      </trans-unit>    </body>  </file></xliff>

配置应用程序以支持多种语言 (Configure the app to serve in multiple languages)

Open angular.json file and add the following configuration.

打开angular.json文件并添加以下配置。

"build": {  ...  "configurations": {    ...    "es": {      "aot": true,      "i18nFile": "src/translate/messages.es.xlf",      "i18nFormat": "xlf",      "i18nLocale": "es",      "i18nMissingTranslation": "error"    }  }},"serve": {  ...  "configurations": {    ...    "es": {      "browserTarget": "i18nDemo:build:es"    }  }}

Here we have added the configuration for the Spanish language. We have provided the path and format for i18n file and set the locale to “es”. When we execute the application, the app’s content will be served from the i18n file path provided.

在这里,我们添加了西班牙语的配置。 我们提供了i18n文件的路径和格式,并将语言环境设置为“ es”。 当我们执行应用程序时,将从提供的i18n文件路径中提供应用程序的内容。

Similarly you can add configuration for other languages.

同样,您可以添加其他语言的配置。

执行演示 (Execution Demo)

Once you have added the configuration for all the languages in angular.json file, run the following command to start the server.

在angular.json文件中添加了所有语言的配置后,请运行以下命令来启动服务器。

ng serve --configuration=es

This will launch the application in “es” configuration and our app will show the Spanish language translations.

这将以“ es”配置启动该应用程序,而我们的应用程序将显示西班牙语翻译。

Refer to the output screen as shown below:

请参考如下所示的输出屏幕:

The configurations that we have defined will only help the app run in the local machine. We cannot change the configuration once the app is launched.

我们定义的配置只会帮助应用程序在本地计算机上运行。 应用启动后,我们将无法更改配置。

A production app will need the application to serve for different languages just by changing the URL. For example, mywebsite.com/es will provide the Spanish version of site, and mywebsite.com/en will provide the English version. In this case, the app will be served from different virtual directories for different languages. We will explore how to do this in next section.

生产应用程序仅通过更改URL就需要该应用程序为不同的语言提供服务。 例如, mywebsite.com/es将提供mywebsite.com/es的西班牙语版本,而mywebsite.com/en将提供英语版本。 在这种情况下,将通过使用不同语言的不同虚拟目录提供该应用程序。 我们将在下一部分中探讨如何执行此操作。

修改应用程序组件以进行生产 (Modify the app component for production)

Open app.component.ts and put in the following code.

打开app.component.ts并输入以下代码。

import { Component, LOCALE_ID, Inject } from '@angular/core';@Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: ['./app.component.css']})export class AppComponent {  title = 'i18nDemo';  languageList = [    { code: 'en', label: 'English' },    { code: 'hi', label: 'हिंदी' },    { code: 'es', label: 'Espanol' }  ];  constructor(@Inject(LOCALE_ID) protected localeId: string) { }}

Here we have defined a list of languages and their locale codes. These locale codes are standard codes. You can easily get a list of languages and the corresponding locale codes by a simple Google search.

在这里,我们定义了语言及其区域代码的列表。 这些区域代码是标准代码。 您可以通过简单的Google搜索轻松获得语言列表和相应的区域代码。

Add the following codes in app.component.html file.

app.component.html文件中添加以下代码。

<ng-container *ngFor="let language of languageList"> <a href="/{{language.code}}/"> <button class="button">{{language.label}}</button> </a></ng-container>

Here we have defined three buttons for three languages. On each button click, the locale id will change and the locale id will be appended to the URL also. This will allow us to serve the application from a different directory.

在这里,我们为三种语言定义了三个按钮。 每次单击按钮时,区域设置ID都会更改,并且区域设置ID也将附加到URL。 这将使我们能够从其他目录提供服务。

Put the following code in app.component.css file to apply styles to these buttons.

将以下代码放入app.component.css文件中,以将样式应用于这些按钮。

.button {  background-color: darkslateblue;  border-radius: 5px;  color: white;  padding: 5px;  width: 10%;  margin: 5px;  text-decoration: none;  cursor: pointer;}

编译应用以进行生产的脚本 (Script to compile the app for production)

We need to have three different serving locations for three different languages. To build the application package for one language for production, we will use the following command:

我们需要为三种不同的语言提供三个不同的服务位置。 要为一种用于生产的语言构建应用程序包,我们将使用以下命令:

ng build --prod --i18n-locale es --i18n-format xlf --i18n-file src/translate/messages.es.xlf --output-path=dist/es --baseHref /es/

Let us understand this command. We provided the locale id for the package, which is “es” for Spanish. We also provide the i18n file path and format. The output path property is required to provide the location for the application package. The baseHref property specifies the base URL from which this package will be served.

让我们了解此命令。 我们提供了该软件包的语言环境ID,西班牙语为“ es”。 我们还提供了i18n文件的路径和格式。 需要输出路径属性来提供应用程序包的位置。 baseHref属性指定将从其提供此程序包的基本URL。

We need to run this command for every language we will provide by changing the i18n file path and baseHref attribute values. However, this will be a cumbersome task if we have a lot of languages. Therefore, we will write a script to generate a package for all languages. Open package.json file and add the following scripts inside the “scripts” section.

我们需要通过更改i18n文件路径和baseHref属性值来为将提供的每种语言运行此命令。 但是,如果我们使用多种语言,这将是一项繁琐的任务。 因此,我们将编写一个脚本以生成所有语言的包。 打开package.json文件,并在“脚本”部分中添加以下脚本。

"build-locale:en": "ng build --prod --i18n-locale en --i18n-format xlf --i18n-file src/translate/messages.en.xlf --output-path=dist/en --baseHref /en/","build-locale:es": "ng build --prod --i18n-locale es --i18n-format xlf --i18n-file src/translate/messages.es.xlf --output-path=dist/es --baseHref /es/","build-locale:hi": " ng build --prod --i18n-locale hi --i18n-format xlf --i18n-file src/translate/messages.hi.xlf --output-path=dist/hi --baseHref /hi/","build-locale": "npm run build-locale:en && npm run build-locale:es && npm run build-locale:hi"

Here we have created three scripts for the three languages we are using. The “build-locale” script will execute all of them at once. All these scripts are key-value pairs. The key names we are using here are customizable and you can use any name of your choice. To create the application package for all the languages, run the following command:

在这里,我们为正在使用的三种语言创建了三个脚本。 “ build-locale”脚本将一次执行所有它们。 所有这些脚本都是键值对。 我们在这里使用的键名是可自定义的,您可以使用任何选择的名称。 要为所有语言创建应用程序包,请运行以下命令:

npm run build-locale

On successful execution, it will create a “dist” folder in the application’s root folder. The dist folder has three sub-folders to serve our application in three different languages. Refer to the image shown below:

成功执行后,它将在应用程序的根文件夹中创建一个“ dist”文件夹。 dist文件夹包含三个子文件夹,以三种不同的语言为我们的应用程序提供服务。 请参考下图:

在Firebase上部署应用程序 (Deploying the application on Firebase)

We will deploy this application on Firebase to see the language change in real time. Refer to my article Hosting A Blazor Application on Firebase and follow the steps mentioned to deploy this Angular app on Firebase.

我们将在Firebase上部署此应用程序,以实时查看语言更改。 请参阅我的文章在Firebase上托管Blazor应用程序,并按照上述步骤在Firebase上部署此Angular应用程序。

Once the application is deployed, you will get the hosting URL. Open the URL and append the baseHref attribute as we defined earlier, to the URL. Hence, the URL will be yoursite.com/es/ for the Spanish language and so on.

部署应用程序后,您将获得托管URL。 打开URL,然后将我们之前定义的baseHref属性附加到URL。 因此,该URL为西班牙语的yoursite.com/es/

The application, which we built here, is hosted at https://i18ndemo-415ef.firebaseapp.com/en/. If you open this URL, you will see the output as shown below:

我们在此处构建的应用程序托管在https://i18ndemo-415ef.firebaseapp.com/en/上 。 如果打开此URL,将看到如下所示的输出:

Click on the links provided. The URL will change and the application will reload in the new language.

单击提供的链接。 URL将更改,应用程序将以新语言重新加载。

结论 (Conclusion)

In this post, we learned how to internationalize our Angular app using i18n tools. We also applied localization to our Angular application. Localization allows us to serve our app in different languages, which helps in extending the reach to a worldwide audience. We also learned how localization works in a production environment by deploying our application on Firebase.

在本文中,我们学习了如何使用i18n工具国际化Angular应用程序。 我们还将本地化应用到了Angular应用程序中。 本地化使我们可以使用不同的语言来服务我们的应用程序,这有助于将覆盖范围扩展到全球受众。 通过在Firebase上部署应用程序,我们还了解了本地化在生产环境中的工作方式。

Get the source code from GitHub and play around for a better understanding.

GitHub获取源代码,并进行更好的理解。

Are you preparing for interviews?! Read my article on C# Coding Questions For Technical Interviews

您正在准备面试吗? 阅读有关技术面试的C#编码问题的文章

也可以看看 (See Also)

Originally published at https://ankitsharmablogs.com/

最初发布在https://ankitsharmablogs.com/

翻译自: https://www.freecodecamp.org/news/how-to-implement-localization-in-angular-using-i18n-tools-a88898b1a0d0/

angular i18n

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现AngularJS 1.4.4的i18n国际化可以通过使用angular-translate库来完成。下面是大致的步骤: 1. 安装angular-translate库,在命令行执行以下命令: ``` npm install angular-translate --save ``` 2. 在HTML引入angular-translate库的js文件,例如: ```html <script src="bower_components/angular-translate/angular-translate.js"></script> ``` 3. 在AngularJS应用程序注册'pascalprecht.translate'模块,例如: ```javascript var myApp = angular.module('myApp', ['pascalprecht.translate']); ``` 4. 配置语言文件,例如: ```javascript myApp.config(function($translateProvider) { $translateProvider.translations('en', { TITLE: 'Hello', FOO: 'This is a paragraph.', BUTTON_LANG_EN: 'english', BUTTON_LANG_DE: 'german' }); $translateProvider.translations('de', { TITLE: 'Hallo', FOO: 'Dies ist ein Absatz.', BUTTON_LANG_EN: 'englisch', BUTTON_LANG_DE: 'deutsch' }); $translateProvider.preferredLanguage('en'); }); ``` 5. 在HTML使用AngularJS提供的指令来实现i18n,例如: ```html <div ng-controller="Ctrl"> <h1>{{ 'TITLE' | translate }}</h1> <p>{{ 'FOO' | translate }}</p> <button ng-click="changeLanguage('en')" translate="BUTTON_LANG_EN"></button> <button ng-click="changeLanguage('de')" translate="BUTTON_LANG_DE"></button> </div> ``` 6. 在控制器定义changeLanguage方法,例如: ```javascript myApp.controller('Ctrl', function ($scope, $translate) { $scope.changeLanguage = function (key) { $translate.use(key); }; }); ``` 以上是基于AngularJS 1.4.4和开发工具Eclipse实现i18n国际化的大致步骤,具体实现会因应用程序的需求而有所不同。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值