Beginnen Sie mit einem Sprachwechsel am App-Wurzelverzeichnis und binden Sie ihn an einen Provider, der die aktuelle Sprache speichert und Nachrichten lädt. Use a selectbox um Optionen vorzustellen und seine zu verbinden change Ereignis zum Aktualisieren der Locale.

In typescript projekte, eigentlich define messages als eine pro-Sprachen-Zuordnung, registrieren sie mit der i18n provider, and expose a translator through binding on your page templates.

Use converters um Zahlen und Daten zu formatieren und die Pluralbildung zu handhaben, sodass UI-Strings über verschiedene Sprachen hinweg korrekt bleiben. Erstellen Sie eine kleine, lokale messages katalog und beim Start laden, um Flashs von nicht übersetztem Text zu vermeiden.

Wenn der Benutzer eine Sprache in der Sprachenauswahl, aktualisiert die App den lokalen Datensatz und lädt neu. messages. Wenn die Locale wird undefined, falls es fehlschlägt, auf Englisch zurückgreifen. Wenn Sie wanted die App zu aktualisieren, um Änderungen sofort widerzuspiegeln, lösen Sie einen changed Ereignis und erneutes Binden betroffener Komponenten.

Halten Sie Übersetzungen organisiert: speichern Sie Schlüssel in einem einzigen Namensraum, verwenden Sie eine leichte page layout, and just Schreiben Sie Tests, die üben registrieren and binding flows. Wenn Sie want Um die Einarbeitung zu beschleunigen, definieren Sie ein gemeinsames Wörterbuch für gängige Phrasen und dokumentieren Sie Ihre unterstützten Sprachen. Aktualisieren Sie. messages and converters wenn Ihre App wächst.

Schritt 1: Installieren Sie das aurelia-i18n-Plugin und fügen Sie eine translation.json hinzu

Install aurelia-i18n plugin and add a translation.json to your project now to enable i18n from the start. Use jspm to align with a bundled workflow or npm for modern builds: jspm install aurelia-i18n --dev; npm i aurelia-i18n --save.

Erstelle eine leichte Wrapper-Komponente, die das Plugin in den Aurelia-Lebenszyklus integriert. Der Wrapper verwaltet das Laden von Lokedaten und stellt eine einfache Übersetzungsfunktion bereit. Rechne mit Konvertern zur Formatierung von Zahlen und Daten und hake sie in die Bindung ein, sodass ein einzelnes converter handles common formatting while converters kann für besondere Bedürfnisse erweitert werden.

Platzieren Sie translation.json neben Ihrem Einstiegspunkt und referenzieren Sie es über den Loader. Ein typischer Pfad ist src/assets/i18n/translation.json, und die Datei sollte mit der App gebündelt werden, um sicherzustellen, dass sie beim Start verfügbar ist, einschließlich auf Safari, wo Offline-Caching das Laden beeinflussen kann.

Example structure for translation.json: { "messages": { "greeting": "Hello, {name}!" }, "labels": { "save": "Save" } }

Strategiehinweise: Verwenden Sie unbestimmte Schlüssel für allgemeine, wiederverwendbare Zeichenketten und spezifische Schlüssel für Benutzeroberflächenfragmente. Ausgewählte Schlüssel beziehen sich auf die benötigten Benutzeroberflächenteile, sodass gewünschte Phrasen im Code lesbar bleiben und Übersetzer genaue Ergebnisse liefern können. Das Projekt sollte sich weiterentwickeln, indem neue Schlüssel unter Nachrichten und Beschriftungen hinzugefügt werden, wenn sich Funktionen ändern, ohne bestehende Übersetzungen zu unterbrechen.

Wenn Sie aureliavalidation-i18n verwenden, richten Sie die Validierungsnachrichten in translation.json so aus, dass der Wrapper benutzerfreundliches Feedback liefern kann. Testen Sie über verschiedene Browser, einschließlich Safari, um sicherzustellen, dass gebündelte Ressourcen korrekt geladen werden und dass sich Gebietsscheinänderungen sofort in der UI widerspiegeln, so dass die Dinge klar werden sollten.

Schritt 2: Erstellen Sie Ordner und Dateien (src/i18n, locales, app.js, main.js)

Erstellen Sie jetzt die Ordner und Dateien und verbinden Sie aurelia-i18n mit Ihrer Aurelia-App, sodass die Lokalisierung beim Start über ein Backend geladen wird, das Locale-Daten bereitstellt. Platzieren Sie die Quell-i18n-Logik in src/i18n und organisieren Sie Übersetzungen in locales; halten Sie sich an Aurelias Namenskonventionen, um Kollisionen zu vermeiden.

  1. Ordnerstruktur und Zweck
    • src/i18n: enthält Konfigurationen, Konverter und alle benutzerdefinierten i18n-Adapter.
    • locales: speichert JSON-Dateipakte pro Sprache, geladen mit einem filesglob-Muster wie locales/**/*.json.
    • app.js: export a konfigurieren Funktion, die das i18n-Plugin, das Backend und eine Standardlokalität (ausgewählt) registriert.
    • main.js: Aurelia starten, das i18n-Plugin registrieren und die App mit Binding starten, um Locale und Sprachmeldungen festzulegen.
  2. app.js Konfiguration
    • Exportierte Funktion: export function configure(aurelia){ ... }
    • Stellen Sie einen Backend-Loader bereit, um Sprachdateien aus dem Pfad 'locales' abzurufen, wobei filesglob like locales/**/*.json.
    • Register aurelia-i18n und setze die Standard-Locale über ausgewählt.
    • Expose a format Helfer oder Konverter, wenn Sie eine benutzerdefinierte Datums- oder Zahlenformatierung benötigen.
  3. Hauptkategorie und Laufzeitbindung
    • main.js startet Aurelia und erstellt das Binding für ein Sprache-Auswahl-Element, z.B. ein <selectbox> gebunden an ausgewählt.
    • Use label Schlüssel von locales um dynamischen Text zu rendern: ${firstname} von den gebundenen Daten (vorname kommt aus Ihrem View-Model).
    • Gibt die konfigurierte App-Instanz zurück, sodass Navigation und Routing mit lokalisiertem Inhalt funktionieren.
  4. Nachrichten und Laufzeitbindung
    • In Ihren Ansichtsvorlagen binden Sie an i18n-Schlüssel über eine Bindung oder Hilfsfunktion, z. B., t('messages.greeting', { firstname: firstname }).
    • Geben Sie einige benannte Übersetzungen an, wie z. B. order and ausgewählt, um zu demonstrieren, wie sich die Locale ohne vollständiges Neuladen geändert werden kann.
    • Definieren Sie Platzhalter und Formatierung in messages um dynamische Werte wie zu unterstützen firstname and aurelias naming.

Beispielhafte Organisation in Ländereinstellungen

Tipp: verwende filesglob um alle Übersetzungen automatisch zu laden, z. B., locales/**/*.json. In Ihren Nachrichten sollten Sie die Schlüssel flach halten oder unter gruppieren. label and messages, so eine Bindung wie binding="i18n.t('messages.welcome', { firstname: firstname })" bleibt sauber und spezifisch.

Step 3: Use a plugin with TypeScript and Aurelia's loader

Install aurelia-i18nt and register it with Aurelia's loader in your TypeScript bootstrap to enable dynamic translation loading. This setup lets the loader fetch translation bundles on demand, so you don't ship all strings upfront. Use the option backend with a loadPath das auf Ihren Server oder statische Dateien verweist und eine Standardeinstellung fallbackLocale.

Configure das Backend, sodass der Loader namespace-spezifische Dateien anfordern kann, wie z. B. /i18n/en/common.json oder /i18n/en/home.json. Wenn ein Schlüssel fehlt, kann es sein, undefined, sodass Sie den ursprünglichen Schlüssel oder eine freundliche Fallback-Option anzeigen können. Behandeln Sie Fehler mit einem try/catch-Block um die Anfrage herum und protokollieren Sie diese in window.console zur Fehlersuche.

Example: in einer Vorlage an Übersetzungen mit dem i18n-Dienst binden. Verwenden Sie Schlüssel wie firstname to render the user's given name and support a namespace greeting. Example: binding with i18n.t('greeting.firstname') or i18n.t('home:firstname') covers different contexts.

TypeScript-Tipp: bieten Sie durch die Deklaration einer kleinen Schnittstelle und das Wrappen des t()-Aufrufs einen typisierten Zugriff auf Schlüssel. Dies wird specific zu Ihrem Projekt und hilft mit binding in Vorlagen. Wenn Sie mit strict mode kompilieren, werden undefinierte Prüfungen zur Kompilierzeit sichtbar.

Ereignisbehandlunglauschen Sie auf Änderungen der Locale über das Plugin-Ereignis und rufen Sie dann eine Aktualisierungsmethode auf, um die Namespace-Bundles neu zu laden. Diese Änderung fließt durch Ihre binding Updates, so Komponenten die neue Sprache widerspiegeln, ohne manuelle DOM-Manipulation.

Backend-Optionen: host translations on a dedicated backend, or serve them as static assets. In a simple setup, you call a request to fetch /locales/{lng}/{ns}.json and store results in memory for quick access. The loader would provide a fall back when the requested resource is not found. This would become powerful when you connect to a real backend, and you can search keys across loaded namespaces to cover cases that users named in the UI expect.

Performance tips: preload common namespaces during app startup, cache results, and avoid repeated network calls. Use around the startup to fetch essential bundles, then cover others on demand. When you test, verify that the key firstname resolves correctly across components, and that an unknown key shows the fallback value or the key itself.

Step 4: Structure the Translation JSON File and keys

Adopt a single translation file for the English locale and place it in a locales folder. Load additional fragments with a glob-like pattern so updates stay centralized without manual edits. Keep the tree shallow and logical to support quick lookups during UI rendering.

Organize by feature areas: header, content, and actions. Inside each area, assign short labels for UI strings. Example:

{

"header": { "title": "Welcome", "subtitle": "App Guide" },

"content": { "welcome": "Hello" },

"actions": { "submit": "Submit" }

}

Create a TypeScript type that mirrors the JSON shape. This type clarifies structure and editors offer autocomplete. A compact approach keeps both runtime and compile-time checks aligned.

Handle date-like strings with simple placeholders and a separate formatting utility. Example: "today": "Today is {date}". The runtime applies a date formatter or a dedicated function, keeping strings readable and plain.

As new screens appear, extend the existing tree to keep consistency. Use a central mapping file as the source of truth, and keep a small set of root sections.

Loading notes: use a loader to fetch the JSON and apply strings by path such as header.title or content.welcome.

Example snippet:

{

"header": { "title": "Welcome", "subtitle": "App Guide" },

"content": { "welcome": "Hello" }

}

Step 5: Set Locale and implement a locale select box

Bind a language-switch control to the active locale and trigger a change on the i18n provider when the user selects a new language.

Configure i18n with i18next-xhr-backend and a filesglob so translations load smoothly across the project. This approach covers loading JSON files for each locale, keeps keys organized, and supports dates and locale-specific messages. Use the provider to persist the chosen language, so users see the correct content on subsequent requests.

Implementation details

// View-model import { I18N } from 'aurelia-i18n'; export class App { static inject = [I18N]; constructor(i18n) { this.i18n = i18n; this.locale = localStorage.getItem('locale') || 'en'; } changeLocale(locale) { this.locale = locale; this.i18n.setLocale(locale); localStorage.setItem('locale', locale); } }

<select value.bind="locale" change.delegate="changeLocale(locale)"> <option value="en">English</option> <option value="ru">Русский</option> <option value="es">Español</option> </select>

In the backend setup, use i18next-xhr-backend with a loadPath and filesglob to cover all locale files. Example: backend: { loadPath: '/locales/{{lng}}/{{ns}}.json', filesGlob: '**/*.json' }. This configuration supports specific language bundles and avoids missing keys during requests. For validation messages and dates, hook aureliavalidation-i18n into your forms so feedback adapts to the current locale, and ensure the provider remains the single source of truth for language data.

Step 6: View, Unit Tests, and saved searches to filter results

Bind all UI labels to locale keys and expose a saved searches panel to filter results. there is a clear path using jspm to load aurelia-i18n and windowintl polyfills, then extend the bundled loader to fetch locale bundles from a backend or static files. With this setup, the interface updates naturally when locale changes, there’s a smooth return to previous filters, and the life of the UI stays consistent. Use an options object to share language, region, and date formats across the view so the experience feels cohesive.

To keep the view fast, implement a valueconverter for dates and numbers and wire it to the current locale. Example: a DateValueConverter formats dates via windowintl when available; otherwise it falls back to ISO. typescript sources in the aurelia-framework handle the converter logic, and you can register the converter globally. Label keys drive all strings, and the saved searches panel uses locale-aware labels as well. This approach would be straightforward to adapt in another module and would scale with more locales.

View bindings and value converters

In the aurelia-framework, bind text to i18n keys using the t binding or i18n.bind, and use valueconverter to format dates with formats chosen by the locale. The loader can load resources from bundled assets or a backend, and you can use jspm to manage the runtime dependencies. Ensure dates and currencies render consistently across Safari by including necessary polyfills and testing with windowintl. The example locale files (en.json, fr.json) keep label values in simple strings so translations stay maintainable.

Unit tests and saved searches

Write unit tests with aurelia-testing to verify that the view renders localized strings and that the saved searches filter results correctly. Extend tests to cover the DateValueConverter across locales, and validate that saved searches persist in localStorage and restore on reload. Use a mock backend in tests if needed and verify the loader returns bundles for each locale. After done, run the tests in your preferred runner; this would reduce regression risk and help you extend i18n coverage there and back.