如何在ngx-translate中的另一个翻译中翻译键

问题描述 投票:0回答:1

我有一个翻译JSON文件,我想在另一种翻译的值内翻译另一种翻译。

{
    "COMPANY_NAME": "Apple",
    "WELCOME_TEXT": "{{ COMPANY_NAME }} welcomes you to California!"
}

我看不到如何使用Angular 9中的ngx-translate来执行此操作,有人可以给我一个指针吗?

angular ngx-translate
1个回答
0
投票

我设法通过实现自定义TranslateCompiler来实现这一目标,如下所示:

我的app.module.ts

// ...
imports: [
  TranslateModule.forRoot({
    compiler: { provide: TranslateCompiler, useClass: CustomTranslationCompiler }
  })
]
/// ...

我的CustomTranslationCompiler.ts

import { TranslateCompiler } from '@ngx-translate/core';

export class CustomTranslationCompiler implements TranslateCompiler {
  /**
   * This function is needed to implement the interface, but doesn't
   * actually seem to be used anywhere
   *
   * @param value The translation value
   * @param lang The current language
   */
  public compile(value: string, lang: string): string | Function {
    return value;
  }

  /**
   * Look at every translation and pre-translate any nested translation keys within them
   *
   * @param translations All of the translations for the app to be compiled
   * @param lang The current language
   */
  public compileTranslations(translations: any, lang: string): any {
    for (const key in translations) {
      if (translations.hasOwnProperty(key)) {
        translations[key] = this.translateNestedTranslation(translations[key], translations);
      }
    }

    return translations;
  }

  /**
   * Use a regex to search for and replace translations inside translations
   * with their translated value
   *
   * @param value The translation value
   * @param translations All of the translations for the app
   */
  private translateNestedTranslation(value: string, translations: Object): string {
    const searchRegex  = /{{\s([A-Z_:]*)\s?}}/g;
    const replaceRegex = /({{\s?[A-Z_:]*\s?}})/g;

    const matches = searchRegex.exec(value);
    if (matches && matches.length > 0) {
      const searchKey = matches[1];

      if (translations.hasOwnProperty(searchKey)) {
        // Replace the full translate syntax with the translated value
        value = value.replace(replaceRegex, translations[searchKey]);
      } else {
        // If we can't find the value, display only the missing key instead of the full translate syntax
        value = value.replace(replaceRegex, searchKey);
        console.error(`Error: Unable to find translation '${searchKey}'!`)
      }
    }

    return value;
  }
}

一些注意事项:

  • 使用这种方法时,转换值中定义的任何转换参数必须小写,以免与搜索正则表达式匹配
  • 搜索和替换正则表达式不同
  • 我不确定为什么从不调用compile()方法。我的翻译作为一个对象而来,所以也许这就是为什么...
© www.soinside.com 2019 - 2024. All rights reserved.