Angular i18n用于包含routerLink的文本,并且需要不同的单词顺序

时间:2018-12-12 12:36:33

标签: angular internationalization angular-i18n

我正在努力寻找最有效的方法来翻译包含routerLink或某些单词应该用html标签包裹的文本( word )。

让我们看看它的外观没有 i18n实现:

example.component.html

<div>
 Hello and welcome to this test example. In order to proceed click on this 
 <a [routerLink]="['settings/subscription']">Link</a>
</div>

现在让我们添加 i18n ,并使用一种可能的方法来处理routerLink: en.json

{
  "WELCOME_LABEL": "Hello and welcome to this test example. In order to proceed click on this,
  "LINK_LABEL": "link"
}

example.component.html

<div>
 {{'WELCOME_LABEL' | translate}} 
 <a [routerLink]="['settings/subscription']">{{'LINK_LABEL' | translate}}</a>
</div>

此方法的问题在于,不同的语言可能具有不同顺序的单词。例如。 “请点击此链接” (使用其他语言)可能会按以下顺序排列:链接在句子的开头或中间。

  

是否有一些通用/官方方法来处理这种情况?

一种解决方法是在组件中获取当前语言环境,然后在其基础上进行if检查。

我不喜欢这种方式,因为我有点跳出i18n的实践,并基于语言环境创建了单独的JSON对象,只是为了满足单词排序的需要。

example.component.ts

constructor(
    @Inject( LOCALE_ID ) protected localeId: string
) {
    console.log(this.localeId);
}

example.component.html

<div *ngIf="localeId === 'en-Us'">
 {{'WELCOME_LABEL_EN' | translate}} 
 <a [routerLink]="['settings/subscription']">{{'LINK_LABEL_EN' | translate}}</a>
</div>
<div *ngIf="localeId === 'otherLanguage'">
 {{'WELCOME_LABEL_1_OTHER' | translate}} 
 <a [routerLink]="['settings/subscription']">{{'LINK_LABEL_OTHER' | translate}}</a>
 {{'WELCOME_LABEL_2_OTHER' | translate}} 
</div>

1 个答案:

答案 0 :(得分:1)

如果您简单地将<div>分为三个部分怎么办?例如,文字开头,链接然后结尾。

<div>
  {{'WELCOME_LABEL_START' | translate}}
  <a [routerLink]="['settings/subscription']">{{'LINK_LABEL' | translate}}</a>
  {{'WELCOME_LABEL_END' | translate}}
</div>

这样,根据语言,您只需将句子分为两部分即可。

{
  "WELCOME_LABEL_START": "In order to proceed, click on this,
  "LINK_LABEL": "link",
  "WELCOME_LABEL_END": " whatever language you have."
}

如果没有必要,您只需将开始/结尾为空。