跳至主要内容

Getting started with Angular 1.5 and ES6: part 6

I18n with Angular Translate

Your application could be required to support multi-languages. There are a few solutions to support i18n in Angular applications.
Angular translate is one of the most populars.
Install angular translate packages.
npm install --save angular-translate angular-translate-storage-cookie angular-translate-storage-local
Next import these files in app.js:
//...
import 'angular-translate';
import 'angular-translate-storage-cookie';
import 'angular-translate-storage-local';
//...
And register angular-translate module.
const requires = [
  'pascalprecht.translate',
 //...
Configure $translateProvider in app.config.js file.
import en from './i18n.en.json';
import zh from './i18n.zh.json';

function AppConfig(/.../, $translateProvider){
//...
  // Adding a translation table for the English language
  $translateProvider.translations('en', en);
  // Adding a translation table for the Chinese language
  $translateProvider.translations('zh', zh);
  // Tell the module what language to use by default
  $translateProvider.preferredLanguage('en');
  // Tell the module to store the language in the local storage
  $translateProvider.useLocalStorage();
}
We use webpack json-loader to load json file.
Install json-loader.
npm install --save json-loader
And configure it in webpack.config.js for loading json file.
{ test: /\.json$/, loader: 'json' },
Add two json files in the app folder.
i18n.en.json:
{
  "posts": "Posts",
  "new-post": "New Post"
}
i18n.zh.json:
{
  "posts": "博文",
  "new-post": "新建博文"
}
Open the navbar template file, replace the text of nav links with:
<li class="nav-item" ui-sref-active="active"><a class="nav-link" href="#" ui-sref="app.posts">{{'posts'|translate}}</a></li>
<li class="nav-item" ui-sref-active="active"><a class="nav-link" href="#" ui-sref="app.new-post">{{'new-post'|translate}}</a></li>
<li class="nav-item" ui-sref-active="active"><a class="nav-link" href="#" ui-sref="app.about">{{'about'|translate}}</a></li>
Angular-translate provides a translate filter to translate the text in links.
Now run the application via executing gulp serve in the project root folder.
i18n-1
As you see the posts, new-post in the navbar are replaced with the texts in our i18n.json for English language. But we have not set about there, it displays the original text, and does not indicate what we had omitted.
There are some approaches to notify developers.
Install angular-translate-handler-log which is an extension of angular-translate.
npm install --save angular-translate-handler-log
Import it in app.js file:
import 'angular-translate-handler-log';
Set it in app.config.js file.
$translateProvider.useMissingTranslationHandlerLog();
When the application is reloaded in Chrome browser, an warning messages will be displayed in the Chrome console.
i18n-2
And you can also handle the exception when the item to be translated is not found.
Define an angular factory.
.factory('customTranslationHandler', function () {
    return function (translationID) {
        // return the following text as a translation 'result' - this will be
        // displayed instead of the language key.
        return '[' + translationID + ']';
    };
})
Use this factory to handle missing translations instead of the former useMissingTranslationHandlerLog.
 $translateProvider.useMissingTranslationHandler('customTranslationHandler');
angular-translate provides a $translate service to change language and set language.
In footer.controller.js, add methods:
setLanguage(key) {
this._$translate.use(key);
}

isLanguage(key) {
return key===this._$translate.use();
} 
In the footer template file, add two buttons in a button group to change languages between Chinese and English.
<div class="btn-group btn-group-sm" role="group">
  <a class="btn" ng-class="($ctrl.isLanguage('zh')) ? 'btn-primary' : 'btn-secondary'" ng-click="$ctrl.setLanguage('zh')">中</a>
  <a class="btn" ng-class="($ctrl.isLanguage('en')) ? 'btn-primary' : 'btn-secondary'" ng-click="$ctrl.setLanguage('en')">EN</a>
</div>
Run this application again.
i18n-3
More about $translate, check official Angular translate docs .
Angular translate support variables in translation text.
For example, translate the welcome info for signin page.
 "welcome-back":"Welcome back,{{name}}"
And use it and replace the placeholder signature with real string you expected here.
this._toastr.success(this._$translate.instant('welcome-back', {
  name: this.data.username
}));
If you want to use advanced pluralization provided by MessageFormat.js.
Just install angular-translate-interpolation-messageformat which bridges angular translate with messageformat:
npm install --save  angular-translate-interpolation-messageformat
Declare we will use it in app.config.js:
$translateProvider.useMessageFormatInterpolation(); 
Now you can use more advanced expression in messages, check Angular translate pluralization docs.

评论

此博客中的热门博文

Create a restful application with AngularJS and Zend 2 framework

Create a restful application with AngularJS and Zend 2 framework This example application uses AngularJS/Bootstrap as frontend and Zend2 Framework as REST API producer. The backend code This backend code reuses the database scheme and codes of the official Zend Tutorial, and REST API support is also from the Zend community. Getting Started with Zend Framework 2 Getting Started with REST and Zend Framework 2 Zend2 provides a   AbstractRestfulController   for RESR API producing. class AlbumController extends AbstractRestfulController { public function getList() { $results = $this->getAlbumTable()->fetchAll(); $data = array(); foreach ($results as $result) { $data[] = $result; } return new JsonModel(array( 'data' => $data) ); } public function get($id) { $album = $this->getAlbumTable()->getAlbum($id); return new JsonModel(array("data" =...

Build a Reactive application with Angular 5 and Spring Boot 2.0

I have created a post to describe Reactive programming supports in Spring 5 and its subprojects, all codes of this article are updated the latest Spring 5 RELEASE, check spring-reactive-sample under my Github account. In this post, I will create a simple blog system, including: A user can sign in and sign out. An authenticated user can create a post. An authenticated user can update a post. Only the user who has ADMIN role can delete a post. All users(including anonymous users) can view post list and post details. An authenticated user can add his comments to a certain post. The backend will be built with the latest Spring 5 reactive stack, including: Spring Boot 2.0, at the moment the latest version is 2.0.0.M7 Spring Data MongoDB supports reactive operations for MongoDB Spring Session adds reactive support for WebSession Spring Security 5 aligns with Spring 5 reactive stack The frontend is an Angular based SPA and it will be generated by Angular CLI. The so...

JPA 2.1: Attribute Converter

JPA 2.1: Attribute Converter If you are using Hibernate, and want a customized type is supported in your Entity class, you could have to write a custom Hibernate Type. JPA 2.1 brings a new feature named attribute converter, which can help you convert your custom class type to JPA supported type. Create an Entity Reuse the   Post   entity class as example. @Entity @Table(name="POSTS") public class Post implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="TITLE") private String title; @Column(name="BODY") private String body; @Temporal(javax.persistence.TemporalType.DATE) @Column(name="CREATED") private Date created; @Column(name="TAGS") private List<String> tags=new ArrayList<>(); } Create an attribute convert...