【问题标题】:Angular i18n for text containing routerLink and requires different word orderAngular i18n 用于包含 routerLink 的文本并且需要不同的字序
【发布时间】:2018-12-12 12:36:32
【问题描述】:

我正在努力寻找最有效的方法来翻译包含 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: zh.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>

【问题讨论】:

    标签: angular internationalization angular-i18n


    【解决方案1】:

    如果您只是将&lt;div&gt; 定义为三个部分会怎样?比如,文本开头,链接,然后是结尾。

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

    如果没有必要,你只需让开始/结束为空。

    【讨论】:

    • 欣赏这个想法,绝对比我的解决方案更可靠
    • 如果您接受答案,我会很高兴,以防解决方案对您来说足够好:)
    • 任何语言都会出现问题,然后可能会改变词序。
    • 不,我看不出有什么问题。正确定义 i18n 文件取决于您。
    【解决方案2】:

    Angular 似乎不支持将指令和非 HTML 元素作为innerHTML 传递。我没试过,但需要注意。


    您可以将整个句子传递为innerHTML 进行翻译,其中包括链接元素。这样就可以动态输出内容了。

    模板:

    <span [innerHTML]="key | translate"></span>
    

    JSON:

    {
      "key": "Please click on <a href='abc.com'>this link</a>."
    }
    

    【讨论】:

    • 但是您在翻译文件中维护代码。如果 href 需要更改,或者您需要添加一个类,或对该元素进行任何其他更改,则必须在所有这些文件中更改它(每种语言一个)。
    • @Roobot 你是对的。除非单词的顺序真的很重要,否则,将句子分成三部分(翻译三个槽)更方便维护。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 2020-03-28
    • 1970-01-01
    • 2018-08-13
    • 2016-08-08
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多