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
Provenance
- Commit
ffaa2e7- Tree
760ffce- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
b8892e7
7 files changed+118 added−16 removed
modified:docs/extensions.rst+67 added-2 removed
35 unmodified lines36 to the environment globals. An internationalized application then has to37 provide at least an `gettext` and optoinally a `ngettext` function into the38 namespace. Either globally or for each rendering.39 40+Environment Methods41+~~~~~~~~~~~~~~~~~~~42+43 After enabling of the extension the environment provides the following44 additional methods:45 43-.. method:: jinja2.Environment.install_gettext_translations(translations)46+.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)47 48 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.52 50-.. method:: jinja2.Environment.install_null_translations()53+ .. versionchanged:: 2.5 newstyle gettext added54 55+.. method:: jinja2.Environment.install_null_translations(newstyle=False)56+57 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.60 61+ .. versionchanged:: 2.5 newstyle gettext added62+63+.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)64+65+ 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.69+70+ If `newstyle` is activated, the callables are wrapped to work like71+ newstyle callables. See :ref:`newstyle-gettext` for more information.72+73+ .. versionadded:: 2.574+75 .. method:: jinja2.Environment.uninstall_gettext_translations()76 77 Uninstall the translations again.78 30 unmodified lines109 110 .. _gettext: http://docs.python.org/dev/library/gettext111 .. _Babel: http://babel.edgewall.org/112 113+.. _newstyle-gettext:114 115+Newstyle Gettext116+~~~~~~~~~~~~~~~~117+118+.. versionadded:: 2.5119+120+Starting with version 2.5 you can use newstyle gettext calls. These are121+inspired by trac's internal gettext functions and are fully supported by122+the babel extraction tool. They might not work as expected by other123+extraction tools in case you are not using Babel's.124+125+What's the big difference between standard and newstyle gettext calls? In126+general they are less to type and less error prone. Also if they are used127+in an autoescaping environment they better support automatic escaping.128+Here some common differences between old and new calls:129+130+standard gettext:131+132+.. sourcecode:: html+jinja133+134+ {{ 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+ )}}139+140+newstyle gettext looks like this instead:141+142+.. sourcecode:: html+jinja143+144+ {{ gettext('Hello World!') }}145+ {{ gettext('Hello %(name)s!', name='World') }}146+ {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}147+148+The advantages of newstyle gettext is that you have less to type and that149+named placeholders become mandatory. The latter sounds like a150+disadvantage but solves a lot of troubles translators are often facing151+when they are unable to switch the positions of two placeholder. With152+newstyle gettext, all format strings look the same.153+154+Furthermore with newstyle gettext, string formatting is also used if no155+placeholders are used which makes all strings behave exactly the same.156+Last but not least are newstyle gettext calls able to properly mark157+strings for autoescaping which solves lots of escaping related issues many158+templates are experiencing over time when using autoescaping.159+160 Expression Statement161 --------------------162 163 **Import name:** `jinja2.ext.do`184 unmodified linesmodified:docs/templates.rst+14 added-2 removed
1237 unmodified lines1238 1239 To use placeholders you can use the `format` filter::1240 1241 {{ _('Hello %(user)s!')|format(user=user.username) }}1242- or1243- {{ _('Hello %s')|format(user.username) }}1242 1243 For multiple placeholders always use keyword arguments to `format` as other1244 languages may not use the words in the same order.1245 1246+.. versionchanged:: 2.51247 1248+If newstyle gettext call are activated (:ref:`newstyle-gettext`), using1249+placeholders is a lot easier:1250+1251+.. sourcecode:: html+jinja1252+1253+ {{ gettext('Hello World!') }}1254+ {{ gettext('Hello %(name)s!', name='World') }}1255+ {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }}1256+1257+Note that the `ngettext` function's format string automatically recieves1258+the count as `num` parameter additionally to the regular parameters.1259+1260+1261 Expression Statement1262 ~~~~~~~~~~~~~~~~~~~~1263 1264 If the expression-statement extension is loaded a tag called `do` is available80 unmodified linesmodified:jinja2/testsuite/ext.py+10 added
309 unmodified lines310 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+ 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: <test></strong>'322+ assert t.render(ae=False) == '<strong>Wert: <test></strong>'323 324+325 class AutoEscapeTestCase(JinjaTestCase):326 327 def test_scoped_setting(self):328 env = Environment(extensions=['jinja2.ext.autoescape'],80 unmodified linesmodified:jinja2/compiler.py+5 added-1 removed
1388 unmodified lines1389 else:1390 self.write(repr(val))1391 1392 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)1398 1399 def visit_Tuple(self, node, frame):1400 self.write('(')1401 idx = -1241 unmodified linesmodified:jinja2/ext.py+13 added-9 removed
128 unmodified lines129 130 def _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 gettext136 unmodified lines274 for var in referenced:275 if var not in variables:276 variables[var] = nodes.Name(var, 'load')277 278- # no variables referenced? no need to escape279- if not referenced:280- singular = singular.replace('%%', '%')281- if plural:282- plural = plural.replace('%%', '%')283-278 if not have_plural:279 plural_expr = None280 elif plural_expr is None:281 parser.fail('pluralize without variables', lineno)282 289- 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 node287 288 def _parse_block(self, parser, allow_pluralize):27 unmodified lines316 assert False, 'internal parser error'317 318 return referenced, concat(buf)319 325- 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('%%', '%')329+330 # singular only:331 if plural_expr is None:332 gettext = nodes.Name('gettext', 'load')333 node = nodes.Call(gettext, [nodes.Const(singular)],11 unmodified lines345 # 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))352 353 # otherwise do that here243 unmodified linesmodified:jinja2/nodes.py+6 added-1 removed
440 unmodified lines441 """A constant template string."""442 fields = ('data',)443 444 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.data451 452 388 unmodified lines841 fields = ('expr',)842 843 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 expr51 unmodified linesmodified:CHANGES+3 added-1 removed
8 unmodified lines9 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.16 17 Version 2.4.118 -------------19 (bugfix release, released on April 20th 2010)165 unmodified lines