Finished support for newstyle gettext translations
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent 4da9034 · Browse files · 3 files·+71 added−21 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+71 added−21 removed
- other:+71 added−21 removed
Provenance
- Commit
b8892e7- Tree
24652b6- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
4da9034
3 files changed+71 added−21 removed
modified:jinja2/testsuite/ext.py+55 added-8 removed
29 unmodified lines30 31 _gettext_re = re.compile(r'_\((.*?)\)(?s)')32 33 34-templates = {34+i18n_templates = {35 'master.html': '<title>{{ page_title|default(_("missing")) }}</title>'36 '{% block body %}{% endblock %}',37 'child.html': '{% extends "master.html" %}{% block body %}'38 '{% trans %}watch out{% endtrans %}{% endblock %}',39 'plural.html': '{% trans user_count %}One user online{% pluralize %}'40 '{{ user_count }} users online{% endtrans %}',41- 'stringformat.html': '{{ _("User: %d")|format(user_count) }}'41+ 'stringformat.html': '{{ _("User: %(num)d")|format(num=user_count) }}'42 }43 44+newstyle_i18n_templates = {45+ 'master.html': '<title>{{ page_title|default(_("missing")) }}</title>'46+ '{% block body %}{% endblock %}',47+ 'child.html': '{% extends "master.html" %}{% block body %}'48+ '{% trans %}watch out{% endtrans %}{% endblock %}',49+ 'plural.html': '{% trans user_count %}One user online{% pluralize %}'50+ '{{ user_count }} users online{% endtrans %}',51+ 'stringformat.html': '{{ _("User: %(num)d", num=user_count) }}',52+ 'ngettext.html': '{{ ngettext("%(num)d apple", "%(num)d apples", apples) }}'53+}54 55+56 languages = {57 'de': {47- 'missing': 'fehlend',48- 'watch out': 'pass auf',49- 'One user online': 'Ein Benutzer online',50- '%(user_count)s users online': '%(user_count)s Benutzer online',51- 'User: %d': 'Benutzer: %d'58+ 'missing': u'fehlend',59+ 'watch out': u'pass auf',60+ 'One user online': u'Ein Benutzer online',61+ '%(user_count)s users online': u'%(user_count)s Benutzer online',62+ 'User: %(num)d': u'Benutzer: %(num)d',63+ '%(num)d apple': u'%(num)d Apfel',64+ '%(num)d apples': u'%(num)d Äpfel'65 }66 }67 68 11 unmodified lines80 return languages.get(language, {}).get(s, s)81 82 83 i18n_env = Environment(71- loader=DictLoader(templates),84+ loader=DictLoader(i18n_templates),85 extensions=['jinja2.ext.i18n']86 )87 i18n_env.globals.update({88 '_': gettext,89 'gettext': gettext,90 'ngettext': ngettext91 })92 93+newstyle_i18n_env = Environment(94+ loader=DictLoader(newstyle_i18n_templates),95+ extensions=['jinja2.ext.i18n']96+)97+newstyle_i18n_env.install_gettext_callables(gettext, ngettext, newstyle=True)98 99 class TestExtension(Extension):100 tags = set(['test'])101 ext_attr = 42181 unmodified lines283 (6, 'ngettext', (u'%(users)s user', u'%(users)s users', None), ['third'])284 ]285 286 287+class NewstyleInternationalizationTestCase(JinjaTestCase):288+289+ def test_trans(self):290+ tmpl = newstyle_i18n_env.get_template('child.html')291+ assert tmpl.render(LANGUAGE='de') == '<title>fehlend</title>pass auf'292+293+ def test_trans_plural(self):294+ tmpl = newstyle_i18n_env.get_template('plural.html')295+ assert tmpl.render(LANGUAGE='de', user_count=1) == 'Ein Benutzer online'296+ assert tmpl.render(LANGUAGE='de', user_count=2) == '2 Benutzer online'297+298+ def test_complex_plural(self):299+ tmpl = newstyle_i18n_env.from_string('{% trans foo=42, count=2 %}{{ count }} item{% '300+ 'pluralize count %}{{ count }} items{% endtrans %}')301+ assert tmpl.render() == '2 items'302+ self.assert_raises(TemplateAssertionError, i18n_env.from_string,303+ '{% trans foo %}...{% pluralize bar %}...{% endtrans %}')304+305+ def test_trans_stringformatting(self):306+ tmpl = newstyle_i18n_env.get_template('stringformat.html')307+ assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'308+309+ def test_newstyle_plural(self):310+ tmpl = newstyle_i18n_env.get_template('ngettext.html')311+ assert tmpl.render(LANGUAGE='de', apples=1) == '1 Apfel'312+ assert tmpl.render(LANGUAGE='de', apples=5) == u'5 Äpfel'313+314+315 class AutoEscapeTestCase(JinjaTestCase):316 317 def test_scoped_setting(self):318 env = Environment(extensions=['jinja2.ext.autoescape'],73 unmodified lines392 def suite():393 suite = unittest.TestSuite()394 suite.addTest(unittest.makeSuite(ExtensionsTestCase))395 suite.addTest(unittest.makeSuite(InternationalizationTestCase))396+ suite.addTest(unittest.makeSuite(NewstyleInternationalizationTestCase))397 suite.addTest(unittest.makeSuite(AutoEscapeTestCase))398 return suitemodified:jinja2/environment.py+7 added
277 unmodified lines278 self.extensions = load_extensions(self, extensions)279 280 _environment_sanity_check(self)281 282+ def add_extension(self, extension):283+ """Adds an extension after the environment was created.284+285+ .. versionadded:: 2.5286+ """287+ load_extensions(self, [extension])288+289 def extend(self, **attributes):290 """Add the items to the instance of the environment if they do not exist291 yet. This is used by :ref:`extensions <writing-extensions>` to register292 callbacks and configuration values without breaking inheritance.810 unmodified linesmodified:jinja2/ext.py+9 added-13 removed
122 unmodified lines123 124 125 @contextfunction126 def _gettext_alias(__context, *args, **kwargs):127- return __context.resolve('gettext')(*args, **kwargs)127+ return __context.call(__context.resolve('gettext'), *args, **kwargs)128 129 130 def _make_new_gettext(func):131 @contextfunction132 def gettext(__context, __string, **variables):133- rv = func(__string)133+ rv = __context.call(func, __string)134 if __context.eval_ctx.autoescape:135 rv = Markup(rv)136 return rv % variables137 return gettext2 unmodified lines140 def _make_new_ngettext(func):141 @contextfunction142 def ngettext(__context, __singular, __plural, num, **variables):143 variables.setdefault('num', num)144- rv = func(__singular, __plural, num)144+ rv = __context.call(func, __singular, __plural, num)145 if __context.eval_ctx.autoescape:146 rv = Markup(rv)147 return rv % variables148 return ngettext136 unmodified lines285 plural_expr = None286 elif plural_expr is None:287 parser.fail('pluralize without variables', lineno)288 289- if variables:290- variables = nodes.Dict([nodes.Pair(nodes.Const(x, lineno=lineno), y)291- for x, y in variables.items()])292- else:293- variables = None294-289 node = self._make_node(singular, plural, variables, plural_expr)290 node.set_lineno(lineno)291 return node292 49 unmodified lines342 # in case newstyle gettext is used, the method is powerful343 # enough to handle the variable expansion and autoescape344 # handling itself345 if self.environment.newstyle_gettext:352- if variables is None:353- variables = nodes.Dict([])354- node.kwargs = variables346+ for key, value in variables.iteritems():347+ node.kwargs.append(nodes.Keyword(key, value))348 349 # otherwise do that here350 else:351 # mark the return value as safe if we are in an352 # environment with autoescaping turned on353 node = nodes.MarkSafeIfAutoescape(node)354 if variables:362- node = nodes.Mod(node, variables)355+ node = nodes.Mod(node, nodes.Dict([356+ nodes.Pair(nodes.Const(key), value)357+ for key, value in variables.items()358+ ]))359 return nodes.Output([node])360 361 362 class ExprStmtExtension(Extension):230 unmodified lines