كيفية تنفيذ الترجمة في Angular باستخدام أدوات i18n

المقدمة

في هذه المقالة ، سنتعلم كيفية جعل تطبيق Angular متاحًا بلغات مختلفة باستخدام i18n والترجمة. سننشئ تطبيق Angular ونهيئه لخدمة المحتوى بثلاث لغات مختلفة. سننشر أيضًا تطبيقنا على Google Firebase ونرى كيف تعمل الترجمة في الوقت الفعلي.

سوف نستخدم Angular 7 و VS Code لتطوير تطبيقنا. ألق نظرة على إخراج التطبيق.

مصدر الرمز

احصل على الكود المصدري لهذا التطبيق من GitHub.

ما هو i18n؟

I18n ، المعروف أيضًا باسم التدويل ، هو عملية جعل تطبيقنا يدعم لغات مختلفة لتوسيع نطاق الوصول إلى جمهور عالمي.

ما هو التعريب؟

الترجمة هي عملية ترجمة التطبيق إلى لغة معينة. نحتاج إلى تطبيق التدويل على التطبيق وبعد ذلك يمكننا توطينه. يتيح لنا التعريب خدمة تطبيقنا بلغات مختلفة.

إنشاء تطبيق Angular 7

تتمثل الخطوة الأولى في إنشاء تطبيق Angular 7. إذا كنت جديدًا على Angular ، أقترح عليك قراءة مقالتي Getting Started with Angular 7.0 لمعرفة كيفية إعداد بيئة تطوير Angular في جهازك.

قم بتشغيل الأمر التالي لإنشاء التطبيق.

ng new i18nDemo

افتح تطبيق i18nDemo باستخدام كود VS.

إعداد مكون التطبيق

افتح app.component.htmlالملف. استبدل النص الموجود بالفعل بالرمز التالي.

Localization Demo in Angular using i18n

Hello, My name is Ankit

This text will remain same in all languages


يمكنك ملاحظة أننا وضعنا علامة <h1> ; and

العلامات ذات السمة i18n. هذه طريقة لإخبار Angular اعتبار هذا النص كمحتوى قابل للترجمة. سوف نستكشف سمة i18n بالتفصيل في القسم التالي.

إنشاء ملف مصدر الترجمة

قم بتشغيل الأمر التالي في CLI لإنشاء ملف مصدر ترجمة.

ng xi18n --output-path translate

سيقوم بإنشاء مجلد يسمى الترجمة وإنشاء messages.xlfملف بداخله. افتح الملف ويمكنك ملاحظة كود XML التالي بداخله.

    Localization Demo in Angular using i18n  app/app.component.html 1    Hello, My name is Ankit  app/app.component.html 5    

يحتوي هذا الملف على قائمة بـ it> tags. These tags will have all the content that was marked for translation using i18n attribute. You can also observe that each ans-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 pr efixed with @@ as we hav e done with

tag in previous section. Hence, the id for

tag is “myName” as we defined it.

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.

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 it> tags. Hence, it is advisable to provide custom ids to each translatable tag to maintain consistency.

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

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.

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

 Localization Demo in Angular using i18n Demostración de localización en angular usando i18n app/app.component.html 1 Hello, My name is Ankit Hola, mi nombre es Ankit app/app.component.html 5 

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

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

 Localization Demo in Angular using i18n I18n का उपयोग कर कोणीय में स्थानीयकरण डेमो app/app.component.html 1 Hello, My name is Ankit हेलो, मेरा नाम अंकित है app/app.component.html 5 

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

 Localization Demo in Angular using i18n Localization Demo in Angular using i18n app/app.component.html 1 Hello, My name is Ankit Hello, My name is Ankit app/app.component.html 5 

Configure the app to serve in multiple languages

Open angular.json file and add the following configuration.

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

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.

ng serve --configuration=es

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

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.

Modify the app component for production

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

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.

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

  {{language.label}} 

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.

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

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

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.

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

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:

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.

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.

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

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

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.

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

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

See Also

  • Understanding Server-side Blazor
  • Understanding Angular 6 Animations
  • ASP.NET Core — Using Highcharts With Angular 5
  • ASP.NET Core — CRUD Using Angular 5 And Entity Framework Core
  • CRUD Operations With ASP.NET Core Using Angular 5 and ADO.NET

Originally published at //ankitsharmablogs.com/