From 2efd6c677d203baf8fa815edc19b066cfa6bdd77 Mon Sep 17 00:00:00 2001 From: ZRunner Date: Wed, 21 Oct 2020 15:16:02 +0200 Subject: [PATCH 1/2] fix lists usages --- i18n/translator.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/i18n/translator.py b/i18n/translator.py index 9ad169b..5a402d0 100644 --- a/i18n/translator.py +++ b/i18n/translator.py @@ -39,6 +39,15 @@ def t(key, **kwargs): def translate(key, **kwargs): locale = kwargs.pop('locale', config.get('locale')) translation = translations.get(key, locale=locale) + if isinstance(translation, list): + # if we can apply plural/formats to the items, let's try + if all(isinstance(data, (str, dict)) for data in translation): + # if needed, we should format every item in the list + if 'count' in kwargs: + translation = [pluralize(key, data, kwargs['count']) for data in translation] + # items may be non-plural dictionnaries, which we cannot format + return [TranslationFormatter(data).format(**kwargs) if isinstance(data, str) else data for data in translation] + return translation if 'count' in kwargs: translation = pluralize(key, translation, kwargs['count']) return TranslationFormatter(translation).format(**kwargs) From 959fbc767de50fa849c256aaab8e0ee4a984d31f Mon Sep 17 00:00:00 2001 From: ZRunner Date: Thu, 22 Oct 2020 12:30:58 +0200 Subject: [PATCH 2/2] add tests units --- i18n/tests/resources/translations/foo.en.yml | 22 ++++++++++++++++++++ i18n/tests/translation_tests.py | 7 +++++++ 2 files changed, 29 insertions(+) diff --git a/i18n/tests/resources/translations/foo.en.yml b/i18n/tests/resources/translations/foo.en.yml index db058a4..708354a 100644 --- a/i18n/tests/resources/translations/foo.en.yml +++ b/i18n/tests/resources/translations/foo.en.yml @@ -7,3 +7,25 @@ en: one: You have a new mail. few: You only have %{count} mails. many: You have %{count} new mails. + months: + - January + - Februrary + - March + - April + - May + - June + - July + - August + - September + - October + - November + - December + welcome: + - Hi %{user} + - Welcome to %{user} + welcome2: + - one: A new user just joined! + many: Some new users just came! + - one: Hello new user! + few: We may need more pylons soon + many: Too many new users, we need more pylons! diff --git a/i18n/tests/translation_tests.py b/i18n/tests/translation_tests.py index a88147b..60c2046 100644 --- a/i18n/tests/translation_tests.py +++ b/i18n/tests/translation_tests.py @@ -131,3 +131,10 @@ def test_skip_locale_root_data_nested_json_dict__other_locale(self): config.set("locale", "en") resource_loader.init_json_loader() self.assertEqual(t('COMMON.EXECUTE', locale="pl"), 'Wykonaj') + + def test_basic_list(self): + self.assertEqual(len(t('foo.months')), 12) + + def test_formatted_list(self): + self.assertEqual(t('foo.welcome', user="someone")[0], "Hi someone") + self.assertEqual(t('foo.welcome2', count=2)[1], "We may need more pylons soon") \ No newline at end of file