Skip to content

Commit 80b24b5

Browse files
authored
Merge pull request #151 from zgoda/lazy_ngettext
Add lazy implementation of ngettext()
2 parents bfd004d + 7035241 commit 80b24b5

3 files changed

Lines changed: 30 additions & 1 deletion

File tree

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,5 @@
55
dist/
66
docs/_build
77
.tox/
8+
.vscode
9+
*.code-workspace

flask_babel/__init__.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,21 @@ def index():
620620
return LazyString(gettext, string, **variables)
621621

622622

623+
def lazy_ngettext(singular, plural, num, **variables):
624+
"""Like :func:`ngettext` but the string returned is lazy which means
625+
it will be translated when it is used as an actual string.
626+
627+
Example::
628+
629+
apples = lazy_ngettext(u'%(num)d Apple', u'%(num)d Apples', num=len(apples))
630+
631+
@app.route('/')
632+
def index():
633+
return unicode(apples)
634+
"""
635+
return LazyString(ngettext, singular, plural, num, **variables)
636+
637+
623638
def lazy_pgettext(context, string, **variables):
624639
"""Like :func:`pgettext` but the string returned is lazy which means
625640
it will be translated when it is used as an actual string.

tests/tests.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import flask
1313
from datetime import datetime, timedelta
1414
import flask_babel as babel
15-
from flask_babel import gettext, ngettext, lazy_gettext, get_translations
15+
from flask_babel import gettext, ngettext, lazy_gettext, lazy_ngettext, get_translations
1616
from babel.support import NullTranslations
1717
from flask_babel._compat import text_type
1818

@@ -266,6 +266,18 @@ def test_lazy_gettext(self):
266266
assert text_type(yes) == 'Yes'
267267
assert yes.__html__() == 'Yes'
268268

269+
def test_lazy_ngettext(self):
270+
app = flask.Flask(__name__)
271+
babel.Babel(app, default_locale='de_DE')
272+
one_apple = lazy_ngettext(u'%(num)s Apple', u'%(num)s Apples', 1)
273+
with app.test_request_context():
274+
assert text_type(one_apple) == '1 Apfel'
275+
assert one_apple.__html__() == '1 Apfel'
276+
two_apples = lazy_ngettext(u'%(num)s Apple', u'%(num)s Apples', 2)
277+
with app.test_request_context():
278+
assert text_type(two_apples) == u'2 Äpfel'
279+
assert two_apples.__html__() == u'2 Äpfel'
280+
269281
def test_list_translations(self):
270282
app = flask.Flask(__name__)
271283
b = babel.Babel(app, default_locale='de_DE')

0 commit comments

Comments
 (0)