我可以使用Angular i18n转换打字稿代码中的字符串文字吗 [英] Can I use Angular i18n to translate string literals in typescript code

查看:52
本文介绍了我可以使用Angular i18n转换打字稿代码中的字符串文字吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Angular的i18n工具对Angular应用进行本地化,该工具可以将HTML模板中的文本提取到xlf文件,然后使用AOT(提前编译)构建整个应用的本地化版本.

I'm localizing my Angular app using Angular's i18n tools, which extract text from HTML templates into an xlf file, and then build a localized version of the whole app using AOT (ahead of time compilation).

我的问题是:可以使用此框架来提取打字稿代码中的字符串文字,以便它们在同一xlf文件中列出并在本地化的AOT构建中替换吗?

My question is: Can is use this framework to extract string literals in typescript code, so they are listed in the same xlf file and replaced in the localized AOT build?

理想情况下,我想在我的打字稿代码中写这样的东西:

Ideally, I'd like to write something like this in my typescript code:

foo() {
   this.bar = i18n('baz');

和字符串'baz'会列在我发送给翻译器的xlf文件中.

and the string 'baz' would be listed in the xlf file I send to my translator.

或者,如果不可能的话,有没有一个图书馆做类似的事情? IE.将打字稿代码中的字符串提取到xlf文件中,然后在运行时或在构建过程中将其替换?

Alternatively, if this isn't possible, is there a library that does something similar? I.e. extract strings from typescript code into an xlf file, then replaces them either at runtime or during build?

推荐答案

我可以确认@JB Nizet在他的答案中所指的是现在在Angular 9中工作,因此可以正常工作:

I can confirm what @JB Nizet is referring to in his answer is now working in Angular 9, so this works:

  foo() {
    const appTitle = $localize`:@@siteTitle:Example Title`;
    // appTitle is now translated based on locale

    titleService.setTitle(appTitle); 
  }

您可以在此处 https://github.com/angular/angular/blob/master/packages/localize/init/index.ts

这篇关于我可以使用Angular i18n转换打字稿代码中的字符串文字吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆