将右到左(rtl)支持添加到本地化的Angular 2+应用程序(例如希伯来语和阿拉伯语)中的最佳做法是什么?我查看了几个教程,包括Internationalization (i18n),但似乎没有覆盖它。我希望,例如,html方向属性(例如<html dir="rtl">
)与应用程序构建步骤中18n属性中定义的翻译一起添加。
可以添加i18n-dir
作为described in the docs。所以,我到目前为止找到的最好的方法是将i18n-dir dir="ltr"
(其中ltr
是默认方向)添加到根组件模板中的根元素(例如app.component.html
),如下所示:
<div i18n-dir dir="ltr">
<!-- The rest of the content -->
</div>
生成翻译文件后,相应的trans-unit
将出现在每个文件中,其中source
包含默认方向,在本例中为ltr
。因此,您只需要将单位的target
设置为rtl
以获得相应的语言。
问题是主要的index.html
(和一些其他文件)不是模板,你不能用它做一些事情(例如翻译)。见this issue。
但因为这是一个简单的过程,我试着自己做:
index.html
的翻译版本并将其插入到命名为rtl
语言代码的文件夹中(在我的例子中为fa
):
SRC / FA / index.html的:
<!doctype html>
<html lang="fa" dir="rtl">
<head>
<meta charset="utf-8">
<title>عنوان برنامه</title>
<base href="/fa/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="manifest" href="manifest.json">
<meta name="theme-color" content="#1976d2">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
</head>
<body>
<app-root></app-root>
<noscript>برای ادامه استفاده از این برنامه لازم است JavaScript را فعال کنید.</noscript>
</body>
</html>
特别是看lang="fa"
和dir="rtl"
和本土文本。production-fa
文件中的相关构建配置(在我的例子中:fa
和angular.json
)中:
"index": "src/fa/index.html"
完成。
你可以用其他语言做同样的事情(甚至ltr
s!因为我们在index.html
做了其他的改变)。
为了更好地理解,我还在package.json
文件中插入了相关的构建脚本:
"start-fa": "ng serve --configuration=fa",
"build-fa": "ng build --configuration=fa",
"build-prod-fa": "ng build --prod --configuration=production-fa",
奖励:manifest.json
文件怎么样(如果你想要一个可安装的PWA)?
第一步就像上面那样。在src/fa/manifest.json
中创建翻译版本:
{
"dir": "rtl",
"lang": "fa",
"name": "نام بلند برنامه",
"short_name": "نام کوتاه",
"theme_color": ...
...
但第二步有点困难。我找不到定义其路径的方法。您可以用这个替换原始(src/manifest.json
)。你必须在构建过程开始之前(而不是在它之后替换dist/.../manifest.json
;因为@angular/service-worker
需要在构建过程中知道它的最终状态)。所以在你的package.json
:
"build-prod-fa": "cp src/fa/manifest.json src/manifest.json && ng build --prod --configuration=production-fa",
并在默认生产版本之前将其恢复为默认版本(在我的情况下,默认语言为en
):
"build-prod": "cp src/en/manifest.json src/manifest.json && ng build --prod",
请注意,关于manifest.json
只需要production
构建很重要。因为serviceWorker
默认情况下仅在这些配置中启用(请参阅angular.json
文件)。
我知道这不是一个理想的解决方案。因为您需要在多个位置编辑源(在这两个文件中)。
截至2017年,似乎Angular团队太忙,太少,不能为角度翻译模块(https://github.com/angular-translate/angular-translate/issues/260)添加从右到左(rtl)的支持。
不过没什么大不了的,因为用原生的JS来做这个很容易...
document.body.setAttribute("dir", "rtl");
根据我的经验,HTML5在正确完成rtl支持方面做得非常好。