如何为 i18n angular 应用程序重定向资产和页面 URL

How to redirect assets and page URLs for i18n angular application

我正在国际化 Angular 11 应用程序。 ng serve 一切正常,但我在部署时遇到问题,因为我无法解决以下问题:

angular.json 文件包含标准内容:

      "i18n": {
        "sourceLocale": "fr",
        "locales": {
          "en": {
            "translation": "src/locale/messages.en.xlf"
          }
        }
      }
...
      "localize": true
...

该应用程序使用 ng build --prod --localize 以 2 种语言构建,在 dist 中生成 2 个 enfr 子文件夹,然后我将其部署到服务器,在以下 .htaccess 文件旁边:

RewriteEngine on
RewriteBase /
RewriteRule ^../index\.html$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (..) /index.html [L]

RewriteCond %{HTTP:Accept-Language} ^en [NC]
RewriteRule ^$ /en/ [R]

RewriteCond %{HTTP:Accept-Language} !^en [NC]
RewriteRule ^$ /fr/ [R]

(请注意 fr 是源和默认语言环境,en 是翻译)

我想问题出在 .htaccess 文件中,因为没有任何内容指定 https://example.com/assets/picture.png 应该转换为 https://example.com/en/assets/picture.png,同样对于 URLs for Angular路线。

你能告诉我如何解决这个问题吗?

注意:通过查看生成网页的源代码,我可以验证它是否包含正确的 href,例如fr:

<!doctype html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <title>MyApp</title>
  <base href="/fr/">

请检查一下,它将帮助您了解一些信息。

custom-link.pipe.ts

@Pipe({
  name: "toLangHref",
})

// *To Tranform  all Links to multiple Languages Links
export class CustomLinkPipe implements PipeTransform {
  constructor(private domSanitizer: DomSanitizer, private router: Router) {}

  transform(value: any, args?: any): any {
    return this.domSanitizer.bypassSecurityTrustHtml(this.tranformHref(value));
  }

  tranformHref(innerHtml: string): string {
    const langCode = this.getLangCode(this.router.url);
    return innerHtml?.replace(/href='/g, `href='/${langCode}`) || innerHtml;
  }

  getLangCode(path: string): string {
    path =
      path?.charAt(0) === "/" &&
      (path?.charAt(3) === "/" ||
        path?.charAt(3) === "?" ||
        path?.charAt(3) === "")
        ? path?.substring(1, 3)
        : "";

    return path;
  }
}

我如何使用它

"api_section_sub_info_en": "Take your parcel shipping to the next level with our market-leading <a href='/tracking-api'>Tracking API</a> and <a href='/tracking-webhook'>Tracking Webhook</a> solutions, which deliver true end-to-end location and status events in real-time.",
"api_section_sub_info_fr": "Faites passer l'expédition de vos colis au niveau supérieur avec nos solutions <a href='/tracking-api'>API</a> de <a href='/tracking-webhook'>suivi et Webhook de suivi leaders du</a> marché, qui fournissent de véritables événements de localisation et de statut de bout en bout en temps réel.",


 <p
     class="mt-4 max-w-2xl text-xl text-gray-500 mx-auto include-link"
     [innerHtml]="lang?.api_section_sub_info | toLangHref"
  ></p>

Here is the result

就我而言,我需要用25种语言翻译整个段落,连link的标签都可以翻译。 您可以使用此方法为您的图像实现:D。祝你好运!

提示:

return innerHtml?.replace(/src='/g, `src='/${langCode}`) || innerHtml;

看起来像下面的作品:

RewriteEngine on
RewriteBase /

# keep index.html unchanged
RewriteRule ^(en|fr)/index\.html$ - [L]

# if the URL has no locale prefix, add it (for French)
RewriteCond %{HTTP:Accept-Language} ^fr [NC]
RewriteRule ^(?!(fr|en))(.*)$ fr/ [L,DPI]

# same for English
RewriteCond %{HTTP:Accept-Language} ^en [NC]
RewriteRule ^(?!(fr|en))(.*)$ en/ [L,DPI]

# at this stage, the URL has a locale prefix
# If the requested resource is not a file/directory, then submit it
# to Angular as a potential route starting with locale 
# => redirect to index.html prefixed with the first 2 letters (= locale)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(..).*$ /index.html [L]