From 97057bc43209c2c6af2e9ed783b8659e6b85b1ec Mon Sep 17 00:00:00 2001 From: Pig Fang Date: Thu, 18 Feb 2021 09:43:23 +0800 Subject: [PATCH] fix order of loading front-end l10n file --- app/Http/View/Composers/FootComposer.php | 6 +----- resources/assets/src/scripts/i18n.ts | 13 ++++++++----- resources/assets/tests/scripts/i18n.test.ts | 1 + resources/views/shared/foot.twig | 1 + 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/app/Http/View/Composers/FootComposer.php b/app/Http/View/Composers/FootComposer.php index 5ba3bbf1..3db0e81c 100644 --- a/app/Http/View/Composers/FootComposer.php +++ b/app/Http/View/Composers/FootComposer.php @@ -39,14 +39,10 @@ class FootComposer public function injectJavaScript(View $view) { $scripts = []; - - $locale = app()->getLocale(); - $scripts[] = [ - 'src' => $this->javascript->generate($locale), - ]; $scripts = $this->filter->apply('scripts', $scripts); $view->with([ + 'i18n' => $this->javascript->generate(app()->getLocale()), 'scripts' => $scripts, 'inline_js' => option('custom_js'), ]); diff --git a/resources/assets/src/scripts/i18n.ts b/resources/assets/src/scripts/i18n.ts index 7374c9f5..17b36f40 100644 --- a/resources/assets/src/scripts/i18n.ts +++ b/resources/assets/src/scripts/i18n.ts @@ -1,15 +1,18 @@ +interface I18nTable { + [key: string]: string | I18nTable | undefined +} + export function t(key: string, parameters = Object.create(null)): string { const segments = key.split('.') - let temp = blessing.i18n as { - [k: string]: string | { [k: string]: string } - } + let temp = blessing.i18n as I18nTable | undefined let result = '' for (const segment of segments) { - if (!temp[segment]) { + /* istanbul ignore next */ + const middle = temp?.[segment] + if (!middle) { return key } - const middle = temp[segment] if (typeof middle === 'string') { result = middle } else { diff --git a/resources/assets/tests/scripts/i18n.test.ts b/resources/assets/tests/scripts/i18n.test.ts index 47fb7709..ea8bc305 100644 --- a/resources/assets/tests/scripts/i18n.test.ts +++ b/resources/assets/tests/scripts/i18n.test.ts @@ -9,5 +9,6 @@ test('translate text', () => { expect(t('a.b.c')).toBe('text') expect(t('a.b.d')).toBe('Hi, :name!') expect(t('a.b.d', { name: 'me' })).toBe('Hi, me!') + expect(t('a.b.e')).toBe('a.b.e') expect(t('d.e')).toBe('d.e') }) diff --git a/resources/views/shared/foot.twig b/resources/views/shared/foot.twig index a6629d5f..5e40f567 100644 --- a/resources/views/shared/foot.twig +++ b/resources/views/shared/foot.twig @@ -1,4 +1,5 @@ + {{ include('assets.app', ignore_missing = true) }} {% for script in scripts %}