Skip to content
Myr

it's now possible to register extensions after an environment

Before adoption: this commit came in with the history the project adopted, so no landing records it.

was created. --HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent b8892e7 · Browse files · 7 files+118 added−16 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+118 added−16 removed

  • other:+118 added−16 removed

7 files+118 added−16 removed

modified:docs/extensions.rst+67 added-2 removed
35 unmodified lines
36to the environment globals. An internationalized application then has to37provide at least an `gettext` and optoinally a `ngettext` function into the38namespace. Either globally or for each rendering.3940Environment Methods41~~~~~~~~~~~~~~~~~~~4243After enabling of the extension the environment provides the following44additional methods:4543.. method:: jinja2.Environment.install_gettext_translations(translations)46.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)4748 Installs a translation globally for that environment. The tranlations49 object provided must implement at least `ugettext` and `ungettext`.50 The `gettext.NullTranslations` and `gettext.GNUTranslations` classes51 as well as `Babel`_\s `Translations` class are supported.5250.. method:: jinja2.Environment.install_null_translations()53 .. versionchanged:: 2.5 newstyle gettext added5455.. method:: jinja2.Environment.install_null_translations(newstyle=False)5657 Install dummy gettext functions. This is useful if you want to prepare58 the application for internationalization but don't want to implement the59 full internationalization system yet.6061 .. versionchanged:: 2.5 newstyle gettext added6263.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)6465 Installs the given `gettext` and `ngettext` callables into the66 environment as globals. They are supposed to behave exactly like the67 standard library's :func:`gettext.ugettext` and68 :func:`gettext.ungettext` functions.6970 If `newstyle` is activated, the callables are wrapped to work like71 newstyle callables. See :ref:`newstyle-gettext` for more information.7273 .. versionadded:: 2.57475.. method:: jinja2.Environment.uninstall_gettext_translations()7677 Uninstall the translations again.78
30 unmodified lines
109110.. _gettext: http://docs.python.org/dev/library/gettext111.. _Babel: http://babel.edgewall.org/112113.. _newstyle-gettext:114115Newstyle Gettext116~~~~~~~~~~~~~~~~117118.. versionadded:: 2.5119120Starting with version 2.5 you can use newstyle gettext calls. These are121inspired by trac's internal gettext functions and are fully supported by122the babel extraction tool. They might not work as expected by other123extraction tools in case you are not using Babel's.124125What's the big difference between standard and newstyle gettext calls? In126general they are less to type and less error prone. Also if they are used127in an autoescaping environment they better support automatic escaping.128Here some common differences between old and new calls:129130standard gettext:131132.. sourcecode:: html+jinja133134 {{ gettext('Hello World!') }}135 {{ gettext('Hello %(name)s!')|format(name='World') }}136 {{ ngettext('%(num)d apple', '%(num)d apples', apples|count)|format(137 num=apples|count138 )}}139140newstyle gettext looks like this instead:141142.. sourcecode:: html+jinja143144 {{ gettext('Hello World!') }}145 {{ gettext('Hello %(name)s!', name='World') }}146 {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}147148The advantages of newstyle gettext is that you have less to type and that149named placeholders become mandatory. The latter sounds like a150disadvantage but solves a lot of troubles translators are often facing151when they are unable to switch the positions of two placeholder. With152newstyle gettext, all format strings look the same.153154Furthermore with newstyle gettext, string formatting is also used if no155placeholders are used which makes all strings behave exactly the same.156Last but not least are newstyle gettext calls able to properly mark157strings for autoescaping which solves lots of escaping related issues many158templates are experiencing over time when using autoescaping.159160Expression Statement161--------------------162163**Import name:** `jinja2.ext.do`
184 unmodified lines
modified:docs/templates.rst+14 added-2 removed
1237 unmodified lines
12381239To use placeholders you can use the `format` filter::12401241 {{ _('Hello %(user)s!')|format(user=user.username) }}1242 or1243 {{ _('Hello %s')|format(user.username) }}12421243For multiple placeholders always use keyword arguments to `format` as other1244languages may not use the words in the same order.12451246.. versionchanged:: 2.512471248If newstyle gettext call are activated (:ref:`newstyle-gettext`), using1249placeholders is a lot easier:12501251.. sourcecode:: html+jinja12521253 {{ gettext('Hello World!') }}1254 {{ gettext('Hello %(name)s!', name='World') }}1255 {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}12561257Note that the `ngettext` function's format string automatically recieves1258the count as `num` parameter additionally to the regular parameters.125912601261Expression Statement1262~~~~~~~~~~~~~~~~~~~~12631264If the expression-statement extension is loaded a tag called `do` is available
80 unmodified lines
modified:jinja2/testsuite/ext.py+10 added
309 unmodified lines
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'313314 def test_autoescape_support(self):315 env = Environment(extensions=['jinja2.ext.autoescape',316 'jinja2.ext.i18n'])317 env.install_gettext_callables(lambda x: u'<strong>Wert: %(name)s</strong>',318 lambda s, p, n: s, newstyle=True)319 t = env.from_string('{% autoescape ae %}{{ gettext("foo", name='320 '"<test>") }}{% endautoescape %}')321 assert t.render(ae=True) == '<strong>Wert: &lt;test&gt;</strong>'322 assert t.render(ae=False) == '<strong>Wert: <test></strong>'323324325class AutoEscapeTestCase(JinjaTestCase):326327 def test_scoped_setting(self):328 env = Environment(extensions=['jinja2.ext.autoescape'],
80 unmodified lines
modified:jinja2/compiler.py+5 added-1 removed
1388 unmodified lines
1389 else:1390 self.write(repr(val))13911392 def visit_TemplateData(self, node, frame):1393 try:1393 self.write(repr(node.as_const(frame.eval_ctx)))1394 self.write(repr(node.as_const(frame.eval_ctx)))1395 except nodes.Impossible:1396 self.write('(context.eval_ctx.autoescape and Markup or identity)(%r)'1397 % node.data)13981399 def visit_Tuple(self, node, frame):1400 self.write('(')1401 idx = -1
241 unmodified lines
modified:jinja2/ext.py+13 added-9 removed
128 unmodified lines
129130def _make_new_gettext(func):131 @contextfunction132 def gettext(__context, __string, **variables):133 rv = __context.call(func, __string)133 rv = __context.call(func, __string)134 if __context.eval_ctx.autoescape:135 rv = Markup(rv)136 return rv % variables137 return gettext
136 unmodified lines
274 for var in referenced:275 if var not in variables:276 variables[var] = nodes.Name(var, 'load')277278 # no variables referenced? no need to escape279 if not referenced:280 singular = singular.replace('%%', '%')281 if plural:282 plural = plural.replace('%%', '%')283278 if not have_plural:279 plural_expr = None280 elif plural_expr is None:281 parser.fail('pluralize without variables', lineno)282289 node = self._make_node(singular, plural, variables, plural_expr)283 node = self._make_node(singular, plural, variables, plural_expr,284 bool(referenced))285 node.set_lineno(lineno)286 return node287288 def _parse_block(self, parser, allow_pluralize):
27 unmodified lines
316 assert False, 'internal parser error'317318 return referenced, concat(buf)319325 def _make_node(self, singular, plural, variables, plural_expr):320 def _make_node(self, singular, plural, variables, plural_expr,321 vars_referenced):322 """Generates a useful node from the data provided."""323 # no variables referenced? no need to escape for old style324 # gettext invocations325 if not vars_referenced and not self.environment.newstyle_gettext:326 singular = singular.replace('%%', '%')327 if plural:328 plural = plural.replace('%%', '%')329330 # singular only:331 if plural_expr is None:332 gettext = nodes.Name('gettext', 'load')333 node = nodes.Call(gettext, [nodes.Const(singular)],
11 unmodified lines
345 # in case newstyle gettext is used, the method is powerful346 # enough to handle the variable expansion and autoescape347 # handling itself348 if self.environment.newstyle_gettext:349 print 'HERE'350 for key, value in variables.iteritems():351 node.kwargs.append(nodes.Keyword(key, value))352353 # otherwise do that here
243 unmodified lines
modified:jinja2/nodes.py+6 added-1 removed
440 unmodified lines
441 """A constant template string."""442 fields = ('data',)443444 def as_const(self, eval_ctx=None):445 if get_eval_context(self, eval_ctx).autoescape:445 eval_ctx = get_eval_context(self, eval_ctx)446 if eval_ctx.volatile:447 raise Impossible()448 if eval_ctx.autoescape:449 return Markup(self.data)450 return self.data451452
388 unmodified lines
841 fields = ('expr',)842843 def as_const(self, eval_ctx=None):844 eval_ctx = get_eval_context(self, eval_ctx)845 if eval_ctx.volatile:846 raise Impossible()847 expr = self.expr.as_const(eval_ctx)848 if eval_ctx.autoescape:849 return Markup(expr)850 return expr
51 unmodified lines
modified:CHANGES+3 added-1 removed
8 unmodified lines
9 long time) by adding support for case insensitive searches.10- fixed a bug for getattribute constant folding.11- support for newstyle gettext translations which result in a12 nicer in-template user interface and more consistent13 catalogs.13 catalogs. (:ref:`newstyle-gettext`)14- it's now possible to register extensions after an environment15 was created.1617Version 2.4.118-------------19(bugfix release, released on April 20th 2010)
165 unmodified lines