Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix lists usages #23

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions i18n/tests/resources/translations/foo.en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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!
7 changes: 7 additions & 0 deletions i18n/tests/translation_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
9 changes: 9 additions & 0 deletions i18n/translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down