blob: 78d2429cd20256d84a11368aa1a2693a5547ed8c [file] [log] [blame]
Armin Ronacher05530932008-04-20 13:27:49 +02001# -*- coding: utf-8 -*-
2"""
3 jinja2.ext
4 ~~~~~~~~~~
5
Armin Ronacherb5124e62008-04-25 00:36:14 +02006 Jinja extensions allow to add custom tags similar to the way django custom
7 tags work. By default two example extensions exist: an i18n and a cache
8 extension.
Armin Ronacher05530932008-04-20 13:27:49 +02009
Armin Ronacher55494e42010-01-22 09:41:48 +010010 :copyright: (c) 2010 by the Jinja Team.
Armin Ronacher05530932008-04-20 13:27:49 +020011 :license: BSD.
12"""
Armin Ronacherb5124e62008-04-25 00:36:14 +020013from collections import deque
Armin Ronacher05530932008-04-20 13:27:49 +020014from jinja2 import nodes
Armin Ronacher4f5008f2008-05-23 23:36:07 +020015from jinja2.defaults import *
Armin Ronacher4f77a302010-07-01 12:15:39 +020016from jinja2.environment import Environment
Armin Ronacher2feed1d2008-04-26 16:26:52 +020017from jinja2.runtime import Undefined, concat
Benjamin Wieganda3152742008-04-28 18:07:52 +020018from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError
Armin Ronacherbd357722009-08-05 20:25:06 +020019from jinja2.utils import contextfunction, import_string, Markup, next
Armin Ronacherb5124e62008-04-25 00:36:14 +020020
21
22# the only real useful gettext functions for a Jinja template. Note
23# that ugettext must be assigned to gettext as Jinja doesn't support
24# non unicode strings.
25GETTEXT_FUNCTIONS = ('_', 'gettext', 'ngettext')
Armin Ronacher05530932008-04-20 13:27:49 +020026
27
Armin Ronacher023b5e92008-05-08 11:03:10 +020028class ExtensionRegistry(type):
Armin Ronacher5c047ea2008-05-23 22:26:45 +020029 """Gives the extension an unique identifier."""
Armin Ronacher023b5e92008-05-08 11:03:10 +020030
31 def __new__(cls, name, bases, d):
32 rv = type.__new__(cls, name, bases, d)
33 rv.identifier = rv.__module__ + '.' + rv.__name__
34 return rv
35
36
Armin Ronacher05530932008-04-20 13:27:49 +020037class Extension(object):
Armin Ronacher7259c762008-04-30 13:03:59 +020038 """Extensions can be used to add extra functionality to the Jinja template
Armin Ronacher9d42abf2008-05-14 18:10:41 +020039 system at the parser level. Custom extensions are bound to an environment
40 but may not store environment specific data on `self`. The reason for
41 this is that an extension can be bound to another environment (for
42 overlays) by creating a copy and reassigning the `environment` attribute.
Armin Ronacher762079c2008-05-08 23:57:56 +020043
44 As extensions are created by the environment they cannot accept any
45 arguments for configuration. One may want to work around that by using
46 a factory function, but that is not possible as extensions are identified
47 by their import name. The correct way to configure the extension is
48 storing the configuration values on the environment. Because this way the
49 environment ends up acting as central configuration storage the
50 attributes may clash which is why extensions have to ensure that the names
51 they choose for configuration are not too generic. ``prefix`` for example
52 is a terrible name, ``fragment_cache_prefix`` on the other hand is a good
53 name as includes the name of the extension (fragment cache).
Armin Ronacher7259c762008-04-30 13:03:59 +020054 """
Armin Ronacher023b5e92008-05-08 11:03:10 +020055 __metaclass__ = ExtensionRegistry
Armin Ronacher05530932008-04-20 13:27:49 +020056
57 #: if this extension parses this is the list of tags it's listening to.
58 tags = set()
59
Armin Ronacher5b3f4dc2010-04-12 14:04:14 +020060 #: the priority of that extension. This is especially useful for
61 #: extensions that preprocess values. A lower value means higher
62 #: priority.
63 #:
64 #: .. versionadded:: 2.4
65 priority = 100
66
Armin Ronacher05530932008-04-20 13:27:49 +020067 def __init__(self, environment):
68 self.environment = environment
69
Armin Ronacher7259c762008-04-30 13:03:59 +020070 def bind(self, environment):
71 """Create a copy of this extension bound to another environment."""
72 rv = object.__new__(self.__class__)
73 rv.__dict__.update(self.__dict__)
74 rv.environment = environment
75 return rv
76
Armin Ronacher9ad96e72008-06-13 22:44:01 +020077 def preprocess(self, source, name, filename=None):
78 """This method is called before the actual lexing and can be used to
79 preprocess the source. The `filename` is optional. The return value
80 must be the preprocessed source.
81 """
82 return source
83
84 def filter_stream(self, stream):
85 """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used
86 to filter tokens returned. This method has to return an iterable of
87 :class:`~jinja2.lexer.Token`\s, but it doesn't have to return a
88 :class:`~jinja2.lexer.TokenStream`.
Armin Ronacherd02fc7d2008-06-14 14:19:47 +020089
90 In the `ext` folder of the Jinja2 source distribution there is a file
91 called `inlinegettext.py` which implements a filter that utilizes this
92 method.
Armin Ronacher9ad96e72008-06-13 22:44:01 +020093 """
94 return stream
95
Armin Ronacher05530932008-04-20 13:27:49 +020096 def parse(self, parser):
Armin Ronacher023b5e92008-05-08 11:03:10 +020097 """If any of the :attr:`tags` matched this method is called with the
98 parser as first argument. The token the parser stream is pointing at
99 is the name token that matched. This method has to return one or a
100 list of multiple nodes.
101 """
Armin Ronacher27069d72008-05-11 19:48:12 +0200102 raise NotImplementedError()
Armin Ronacher023b5e92008-05-08 11:03:10 +0200103
104 def attr(self, name, lineno=None):
105 """Return an attribute node for the current extension. This is useful
Armin Ronacher53278a32011-01-24 01:16:00 +0100106 to pass constants on extensions to generated template code.
107
108 ::
Armin Ronacher023b5e92008-05-08 11:03:10 +0200109
Armin Ronacher69e12db2008-05-12 09:00:03 +0200110 self.attr('_my_attribute', lineno=lineno)
Armin Ronacher023b5e92008-05-08 11:03:10 +0200111 """
112 return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
Armin Ronacher05530932008-04-20 13:27:49 +0200113
Armin Ronacher27069d72008-05-11 19:48:12 +0200114 def call_method(self, name, args=None, kwargs=None, dyn_args=None,
115 dyn_kwargs=None, lineno=None):
Armin Ronacher69e12db2008-05-12 09:00:03 +0200116 """Call a method of the extension. This is a shortcut for
117 :meth:`attr` + :class:`jinja2.nodes.Call`.
118 """
Armin Ronacher27069d72008-05-11 19:48:12 +0200119 if args is None:
120 args = []
121 if kwargs is None:
122 kwargs = []
123 return nodes.Call(self.attr(name, lineno=lineno), args, kwargs,
124 dyn_args, dyn_kwargs, lineno=lineno)
125
Armin Ronacher05530932008-04-20 13:27:49 +0200126
Armin Ronacher5c047ea2008-05-23 22:26:45 +0200127@contextfunction
Armin Ronacher4da90342010-05-29 17:35:10 +0200128def _gettext_alias(__context, *args, **kwargs):
Armin Ronacherb8892e72010-05-29 17:58:06 +0200129 return __context.call(__context.resolve('gettext'), *args, **kwargs)
Armin Ronacher4da90342010-05-29 17:35:10 +0200130
131
132def _make_new_gettext(func):
133 @contextfunction
134 def gettext(__context, __string, **variables):
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200135 rv = __context.call(func, __string)
Armin Ronacher4da90342010-05-29 17:35:10 +0200136 if __context.eval_ctx.autoescape:
137 rv = Markup(rv)
138 return rv % variables
139 return gettext
140
141
142def _make_new_ngettext(func):
143 @contextfunction
Armin Ronacherb98dad92010-05-29 22:31:17 +0200144 def ngettext(__context, __singular, __plural, __num, **variables):
145 variables.setdefault('num', __num)
146 rv = __context.call(func, __singular, __plural, __num)
Armin Ronacher4da90342010-05-29 17:35:10 +0200147 if __context.eval_ctx.autoescape:
148 rv = Markup(rv)
149 return rv % variables
150 return ngettext
Armin Ronacher5c047ea2008-05-23 22:26:45 +0200151
152
Armin Ronachered98cac2008-05-07 08:42:11 +0200153class InternationalizationExtension(Extension):
Armin Ronacher762079c2008-05-08 23:57:56 +0200154 """This extension adds gettext support to Jinja2."""
Armin Ronacherb5124e62008-04-25 00:36:14 +0200155 tags = set(['trans'])
156
Armin Ronacher4720c362008-09-06 16:15:38 +0200157 # TODO: the i18n extension is currently reevaluating values in a few
158 # situations. Take this example:
159 # {% trans count=something() %}{{ count }} foo{% pluralize
160 # %}{{ count }} fooss{% endtrans %}
161 # something is called twice here. One time for the gettext value and
162 # the other time for the n-parameter of the ngettext function.
163
Armin Ronacherb5124e62008-04-25 00:36:14 +0200164 def __init__(self, environment):
165 Extension.__init__(self, environment)
Armin Ronacher5c047ea2008-05-23 22:26:45 +0200166 environment.globals['_'] = _gettext_alias
Armin Ronacher762079c2008-05-08 23:57:56 +0200167 environment.extend(
168 install_gettext_translations=self._install,
169 install_null_translations=self._install_null,
Armin Ronacher4da90342010-05-29 17:35:10 +0200170 install_gettext_callables=self._install_callables,
Armin Ronacher762079c2008-05-08 23:57:56 +0200171 uninstall_gettext_translations=self._uninstall,
Armin Ronacher4da90342010-05-29 17:35:10 +0200172 extract_translations=self._extract,
173 newstyle_gettext=False
Armin Ronacher762079c2008-05-08 23:57:56 +0200174 )
175
Armin Ronacher4da90342010-05-29 17:35:10 +0200176 def _install(self, translations, newstyle=None):
Armin Ronacher32133552008-09-15 14:35:01 +0200177 gettext = getattr(translations, 'ugettext', None)
178 if gettext is None:
179 gettext = translations.gettext
180 ngettext = getattr(translations, 'ungettext', None)
181 if ngettext is None:
182 ngettext = translations.ngettext
Armin Ronacher4da90342010-05-29 17:35:10 +0200183 self._install_callables(gettext, ngettext, newstyle)
Armin Ronacher762079c2008-05-08 23:57:56 +0200184
Armin Ronacher4da90342010-05-29 17:35:10 +0200185 def _install_null(self, newstyle=None):
186 self._install_callables(
187 lambda x: x,
188 lambda s, p, n: (n != 1 and (p,) or (s,))[0],
189 newstyle
190 )
191
192 def _install_callables(self, gettext, ngettext, newstyle=None):
193 if newstyle is not None:
194 self.environment.newstyle_gettext = newstyle
195 if self.environment.newstyle_gettext:
196 gettext = _make_new_gettext(gettext)
197 ngettext = _make_new_ngettext(ngettext)
Armin Ronacher762079c2008-05-08 23:57:56 +0200198 self.environment.globals.update(
Armin Ronacher4da90342010-05-29 17:35:10 +0200199 gettext=gettext,
200 ngettext=ngettext
Armin Ronacher762079c2008-05-08 23:57:56 +0200201 )
202
203 def _uninstall(self, translations):
204 for key in 'gettext', 'ngettext':
205 self.environment.globals.pop(key, None)
206
207 def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):
208 if isinstance(source, basestring):
209 source = self.environment.parse(source)
210 return extract_from_ast(source, gettext_functions)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200211
212 def parse(self, parser):
213 """Parse a translatable tag."""
Armin Ronacherbd357722009-08-05 20:25:06 +0200214 lineno = next(parser.stream).lineno
Armin Ronacherb98dad92010-05-29 22:31:17 +0200215 num_called_num = False
Armin Ronacherb5124e62008-04-25 00:36:14 +0200216
Armin Ronacherb5124e62008-04-25 00:36:14 +0200217 # find all the variables referenced. Additionally a variable can be
218 # defined in the body of the trans block too, but this is checked at
219 # a later state.
220 plural_expr = None
Florian Apolloner79c84752012-01-18 17:47:54 +0100221 plural_expr_assignment = None
Armin Ronacherb5124e62008-04-25 00:36:14 +0200222 variables = {}
Armin Ronacher7647d1c2009-01-05 12:16:46 +0100223 while parser.stream.current.type != 'block_end':
Armin Ronacherb5124e62008-04-25 00:36:14 +0200224 if variables:
225 parser.stream.expect('comma')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200226
227 # skip colon for python compatibility
Armin Ronacherfdf95302008-05-11 22:20:51 +0200228 if parser.stream.skip_if('colon'):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200229 break
230
Armin Ronacherb5124e62008-04-25 00:36:14 +0200231 name = parser.stream.expect('name')
232 if name.value in variables:
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200233 parser.fail('translatable variable %r defined twice.' %
234 name.value, name.lineno,
235 exc=TemplateAssertionError)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200236
237 # expressions
Armin Ronacher7647d1c2009-01-05 12:16:46 +0100238 if parser.stream.current.type == 'assign':
Armin Ronacherbd357722009-08-05 20:25:06 +0200239 next(parser.stream)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200240 variables[name.value] = var = parser.parse_expression()
241 else:
242 variables[name.value] = var = nodes.Name(name.value, 'load')
Armin Ronacherb98dad92010-05-29 22:31:17 +0200243
Armin Ronacherb5124e62008-04-25 00:36:14 +0200244 if plural_expr is None:
Florian Apolloner5a25a472012-01-18 17:08:48 +0100245 if isinstance(var, nodes.Call):
Florian Apolloner79c84752012-01-18 17:47:54 +0100246 plural_expr = nodes.Name('_trans', 'load')
247 variables[name.value] = plural_expr
248 plural_expr_assignment = nodes.Assign(
249 nodes.Name('_trans', 'store'), var)
Florian Apolloner5a25a472012-01-18 17:08:48 +0100250 else:
251 plural_expr = var
Armin Ronacherb98dad92010-05-29 22:31:17 +0200252 num_called_num = name.value == 'num'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200253
Armin Ronacherb5124e62008-04-25 00:36:14 +0200254 parser.stream.expect('block_end')
255
256 plural = plural_names = None
257 have_plural = False
258 referenced = set()
259
260 # now parse until endtrans or pluralize
261 singular_names, singular = self._parse_block(parser, True)
262 if singular_names:
263 referenced.update(singular_names)
264 if plural_expr is None:
265 plural_expr = nodes.Name(singular_names[0], 'load')
Armin Ronacherb98dad92010-05-29 22:31:17 +0200266 num_called_num = singular_names[0] == 'num'
Armin Ronacherb5124e62008-04-25 00:36:14 +0200267
268 # if we have a pluralize block, we parse that too
269 if parser.stream.current.test('name:pluralize'):
270 have_plural = True
Armin Ronacherbd357722009-08-05 20:25:06 +0200271 next(parser.stream)
Armin Ronacher7647d1c2009-01-05 12:16:46 +0100272 if parser.stream.current.type != 'block_end':
Armin Ronacher4720c362008-09-06 16:15:38 +0200273 name = parser.stream.expect('name')
274 if name.value not in variables:
275 parser.fail('unknown variable %r for pluralization' %
276 name.value, name.lineno,
277 exc=TemplateAssertionError)
278 plural_expr = variables[name.value]
Armin Ronacherb98dad92010-05-29 22:31:17 +0200279 num_called_num = name.value == 'num'
Armin Ronacherb5124e62008-04-25 00:36:14 +0200280 parser.stream.expect('block_end')
281 plural_names, plural = self._parse_block(parser, False)
Armin Ronacherbd357722009-08-05 20:25:06 +0200282 next(parser.stream)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200283 referenced.update(plural_names)
284 else:
Armin Ronacherbd357722009-08-05 20:25:06 +0200285 next(parser.stream)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200286
287 # register free names as simple name expressions
288 for var in referenced:
289 if var not in variables:
290 variables[var] = nodes.Name(var, 'load')
291
Armin Ronacherb5124e62008-04-25 00:36:14 +0200292 if not have_plural:
293 plural_expr = None
294 elif plural_expr is None:
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200295 parser.fail('pluralize without variables', lineno)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200296
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200297 node = self._make_node(singular, plural, variables, plural_expr,
Armin Ronacher4f77a302010-07-01 12:15:39 +0200298 bool(referenced),
299 num_called_num and have_plural)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200300 node.set_lineno(lineno)
Florian Apolloner79c84752012-01-18 17:47:54 +0100301 if plural_expr_assignment is not None:
302 return [plural_expr_assignment, node]
303 else:
304 return node
Armin Ronacherb5124e62008-04-25 00:36:14 +0200305
306 def _parse_block(self, parser, allow_pluralize):
307 """Parse until the next block tag with a given name."""
308 referenced = []
309 buf = []
310 while 1:
Armin Ronacher7647d1c2009-01-05 12:16:46 +0100311 if parser.stream.current.type == 'data':
Armin Ronacherb5124e62008-04-25 00:36:14 +0200312 buf.append(parser.stream.current.value.replace('%', '%%'))
Armin Ronacherbd357722009-08-05 20:25:06 +0200313 next(parser.stream)
Armin Ronacher7647d1c2009-01-05 12:16:46 +0100314 elif parser.stream.current.type == 'variable_begin':
Armin Ronacherbd357722009-08-05 20:25:06 +0200315 next(parser.stream)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200316 name = parser.stream.expect('name').value
317 referenced.append(name)
318 buf.append('%%(%s)s' % name)
319 parser.stream.expect('variable_end')
Armin Ronacher7647d1c2009-01-05 12:16:46 +0100320 elif parser.stream.current.type == 'block_begin':
Armin Ronacherbd357722009-08-05 20:25:06 +0200321 next(parser.stream)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200322 if parser.stream.current.test('name:endtrans'):
323 break
324 elif parser.stream.current.test('name:pluralize'):
325 if allow_pluralize:
326 break
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200327 parser.fail('a translatable section can have only one '
328 'pluralize section')
329 parser.fail('control structures in translatable sections are '
330 'not allowed')
Armin Ronacherd02fc7d2008-06-14 14:19:47 +0200331 elif parser.stream.eos:
332 parser.fail('unclosed translation block')
Armin Ronacherb5124e62008-04-25 00:36:14 +0200333 else:
334 assert False, 'internal parser error'
335
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200336 return referenced, concat(buf)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200337
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200338 def _make_node(self, singular, plural, variables, plural_expr,
Armin Ronacherb98dad92010-05-29 22:31:17 +0200339 vars_referenced, num_called_num):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200340 """Generates a useful node from the data provided."""
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200341 # no variables referenced? no need to escape for old style
Armin Ronacher4cccc222010-07-06 11:37:45 +0200342 # gettext invocations only if there are vars.
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200343 if not vars_referenced and not self.environment.newstyle_gettext:
344 singular = singular.replace('%%', '%')
345 if plural:
346 plural = plural.replace('%%', '%')
347
Armin Ronacherb5124e62008-04-25 00:36:14 +0200348 # singular only:
349 if plural_expr is None:
350 gettext = nodes.Name('gettext', 'load')
351 node = nodes.Call(gettext, [nodes.Const(singular)],
352 [], None, None)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200353
354 # singular and plural
355 else:
356 ngettext = nodes.Name('ngettext', 'load')
357 node = nodes.Call(ngettext, [
358 nodes.Const(singular),
359 nodes.Const(plural),
360 plural_expr
361 ], [], None, None)
Armin Ronacherd84ec462008-04-29 13:43:16 +0200362
Armin Ronacher4da90342010-05-29 17:35:10 +0200363 # in case newstyle gettext is used, the method is powerful
364 # enough to handle the variable expansion and autoescape
365 # handling itself
366 if self.environment.newstyle_gettext:
Armin Ronacherb8892e72010-05-29 17:58:06 +0200367 for key, value in variables.iteritems():
Armin Ronacherb98dad92010-05-29 22:31:17 +0200368 # the function adds that later anyways in case num was
369 # called num, so just skip it.
370 if num_called_num and key == 'num':
371 continue
Armin Ronacherb8892e72010-05-29 17:58:06 +0200372 node.kwargs.append(nodes.Keyword(key, value))
Armin Ronacherd84ec462008-04-29 13:43:16 +0200373
Armin Ronacher4da90342010-05-29 17:35:10 +0200374 # otherwise do that here
375 else:
376 # mark the return value as safe if we are in an
377 # environment with autoescaping turned on
378 node = nodes.MarkSafeIfAutoescape(node)
379 if variables:
Armin Ronacherb8892e72010-05-29 17:58:06 +0200380 node = nodes.Mod(node, nodes.Dict([
381 nodes.Pair(nodes.Const(key), value)
382 for key, value in variables.items()
383 ]))
Armin Ronacherb5124e62008-04-25 00:36:14 +0200384 return nodes.Output([node])
385
386
Armin Ronacher5d2733f2008-05-15 23:26:52 +0200387class ExprStmtExtension(Extension):
388 """Adds a `do` tag to Jinja2 that works like the print statement just
389 that it doesn't print the return value.
390 """
391 tags = set(['do'])
392
393 def parse(self, parser):
Armin Ronacherbd357722009-08-05 20:25:06 +0200394 node = nodes.ExprStmt(lineno=next(parser.stream).lineno)
Armin Ronacher5d2733f2008-05-15 23:26:52 +0200395 node.node = parser.parse_tuple()
396 return node
397
398
Armin Ronacher3da90312008-05-23 16:37:28 +0200399class LoopControlExtension(Extension):
400 """Adds break and continue to the template engine."""
401 tags = set(['break', 'continue'])
402
403 def parse(self, parser):
Armin Ronacherbd357722009-08-05 20:25:06 +0200404 token = next(parser.stream)
Armin Ronacher3da90312008-05-23 16:37:28 +0200405 if token.value == 'break':
406 return nodes.Break(lineno=token.lineno)
407 return nodes.Continue(lineno=token.lineno)
408
409
Armin Ronacher9b4cc9f2010-02-07 03:55:15 +0100410class WithExtension(Extension):
411 """Adds support for a django-like with block."""
412 tags = set(['with'])
413
414 def parse(self, parser):
415 node = nodes.Scope(lineno=next(parser.stream).lineno)
416 assignments = []
417 while parser.stream.current.type != 'block_end':
418 lineno = parser.stream.current.lineno
419 if assignments:
420 parser.stream.expect('comma')
421 target = parser.parse_assign_target()
422 parser.stream.expect('assign')
423 expr = parser.parse_expression()
424 assignments.append(nodes.Assign(target, expr, lineno=lineno))
425 node.body = assignments + \
426 list(parser.parse_statements(('name:endwith',),
427 drop_needle=True))
428 return node
429
430
Armin Ronacher8346bd72010-03-14 19:43:47 +0100431class AutoEscapeExtension(Extension):
432 """Changes auto escape rules for a scope."""
433 tags = set(['autoescape'])
434
435 def parse(self, parser):
436 node = nodes.ScopedEvalContextModifier(lineno=next(parser.stream).lineno)
437 node.options = [
438 nodes.Keyword('autoescape', parser.parse_expression())
439 ]
440 node.body = parser.parse_statements(('name:endautoescape',),
441 drop_needle=True)
442 return nodes.Scope([node])
443
444
Armin Ronacherabd36572008-06-27 08:45:19 +0200445def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS,
446 babel_style=True):
447 """Extract localizable strings from the given template node. Per
448 default this function returns matches in babel style that means non string
449 parameters as well as keyword arguments are returned as `None`. This
450 allows Babel to figure out what you really meant if you are using
451 gettext functions that allow keyword arguments for placeholder expansion.
452 If you don't want that behavior set the `babel_style` parameter to `False`
453 which causes only strings to be returned and parameters are always stored
454 in tuples. As a consequence invalid gettext calls (calls without a single
455 string parameter or string parameters after non-string parameters) are
456 skipped.
457
458 This example explains the behavior:
459
460 >>> from jinja2 import Environment
461 >>> env = Environment()
462 >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')
463 >>> list(extract_from_ast(node))
464 [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]
465 >>> list(extract_from_ast(node, babel_style=False))
466 [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]
Armin Ronacherb5124e62008-04-25 00:36:14 +0200467
468 For every string found this function yields a ``(lineno, function,
469 message)`` tuple, where:
470
471 * ``lineno`` is the number of the line on which the string was found,
472 * ``function`` is the name of the ``gettext`` function used (if the
473 string was extracted from embedded Python code), and
474 * ``message`` is the string itself (a ``unicode`` object, or a tuple
475 of ``unicode`` objects for functions with multiple string arguments).
Armin Ronacher531578d2010-02-06 16:34:54 +0100476
477 This extraction function operates on the AST and is because of that unable
478 to extract any comments. For comment support you have to use the babel
479 extraction interface or extract comments yourself.
Armin Ronacherb5124e62008-04-25 00:36:14 +0200480 """
481 for node in node.find_all(nodes.Call):
482 if not isinstance(node.node, nodes.Name) or \
483 node.node.name not in gettext_functions:
484 continue
485
486 strings = []
487 for arg in node.args:
488 if isinstance(arg, nodes.Const) and \
489 isinstance(arg.value, basestring):
490 strings.append(arg.value)
491 else:
492 strings.append(None)
493
Armin Ronacherabd36572008-06-27 08:45:19 +0200494 for arg in node.kwargs:
495 strings.append(None)
496 if node.dyn_args is not None:
497 strings.append(None)
498 if node.dyn_kwargs is not None:
499 strings.append(None)
500
501 if not babel_style:
502 strings = tuple(x for x in strings if x is not None)
503 if not strings:
504 continue
Armin Ronacherb5124e62008-04-25 00:36:14 +0200505 else:
Armin Ronacherabd36572008-06-27 08:45:19 +0200506 if len(strings) == 1:
507 strings = strings[0]
508 else:
509 strings = tuple(strings)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200510 yield node.lineno, node.node.name, strings
511
512
Armin Ronacher531578d2010-02-06 16:34:54 +0100513class _CommentFinder(object):
514 """Helper class to find comments in a token stream. Can only
515 find comments for gettext calls forwards. Once the comment
516 from line 4 is found, a comment for line 1 will not return a
517 usable value.
518 """
519
520 def __init__(self, tokens, comment_tags):
521 self.tokens = tokens
522 self.comment_tags = comment_tags
523 self.offset = 0
524 self.last_lineno = 0
525
526 def find_backwards(self, offset):
527 try:
528 for _, token_type, token_value in \
529 reversed(self.tokens[self.offset:offset]):
530 if token_type in ('comment', 'linecomment'):
531 try:
532 prefix, comment = token_value.split(None, 1)
533 except ValueError:
534 continue
535 if prefix in self.comment_tags:
536 return [comment.rstrip()]
537 return []
538 finally:
539 self.offset = offset
540
541 def find_comments(self, lineno):
542 if not self.comment_tags or self.last_lineno > lineno:
543 return []
544 for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset:]):
545 if token_lineno > lineno:
546 return self.find_backwards(self.offset + idx)
547 return self.find_backwards(len(self.tokens))
548
549
Armin Ronacherb5124e62008-04-25 00:36:14 +0200550def babel_extract(fileobj, keywords, comment_tags, options):
551 """Babel extraction method for Jinja templates.
552
Armin Ronacher531578d2010-02-06 16:34:54 +0100553 .. versionchanged:: 2.3
554 Basic support for translation comments was added. If `comment_tags`
555 is now set to a list of keywords for extraction, the extractor will
556 try to find the best preceeding comment that begins with one of the
557 keywords. For best results, make sure to not have more than one
558 gettext call in one line of code and the matching comment in the
559 same line or the line before.
560
Armin Ronacher4f77a302010-07-01 12:15:39 +0200561 .. versionchanged:: 2.5.1
562 The `newstyle_gettext` flag can be set to `True` to enable newstyle
563 gettext calls.
564
Armin Ronacher11619152011-12-15 11:50:27 +0100565 .. versionchanged:: 2.7
566 A `silent` option can now be provided. If set to `False` template
567 syntax errors are propagated instead of being ignored.
568
Armin Ronacherb5124e62008-04-25 00:36:14 +0200569 :param fileobj: the file-like object the messages should be extracted from
570 :param keywords: a list of keywords (i.e. function names) that should be
571 recognized as translation functions
572 :param comment_tags: a list of translator tags to search for and include
Armin Ronacher531578d2010-02-06 16:34:54 +0100573 in the results.
Armin Ronacherb5124e62008-04-25 00:36:14 +0200574 :param options: a dictionary of additional options (optional)
575 :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
576 (comments will be empty currently)
577 """
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200578 extensions = set()
Armin Ronacherb5124e62008-04-25 00:36:14 +0200579 for extension in options.get('extensions', '').split(','):
580 extension = extension.strip()
581 if not extension:
582 continue
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200583 extensions.add(import_string(extension))
584 if InternationalizationExtension not in extensions:
585 extensions.add(InternationalizationExtension)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200586
Armin Ronacher4f77a302010-07-01 12:15:39 +0200587 def getbool(options, key, default=False):
Armin Ronacher11619152011-12-15 11:50:27 +0100588 return options.get(key, str(default)).lower() in \
589 ('1', 'on', 'yes', 'true')
Armin Ronacher4f77a302010-07-01 12:15:39 +0200590
Armin Ronacher11619152011-12-15 11:50:27 +0100591 silent = getbool(options, 'silent', True)
Armin Ronacher4f77a302010-07-01 12:15:39 +0200592 environment = Environment(
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200593 options.get('block_start_string', BLOCK_START_STRING),
594 options.get('block_end_string', BLOCK_END_STRING),
595 options.get('variable_start_string', VARIABLE_START_STRING),
596 options.get('variable_end_string', VARIABLE_END_STRING),
597 options.get('comment_start_string', COMMENT_START_STRING),
598 options.get('comment_end_string', COMMENT_END_STRING),
599 options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200600 options.get('line_comment_prefix') or LINE_COMMENT_PREFIX,
Armin Ronacher4f77a302010-07-01 12:15:39 +0200601 getbool(options, 'trim_blocks', TRIM_BLOCKS),
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200602 NEWLINE_SEQUENCE, frozenset(extensions),
Armin Ronacher4f77a302010-07-01 12:15:39 +0200603 cache_size=0,
604 auto_reload=False
Armin Ronacherb5124e62008-04-25 00:36:14 +0200605 )
606
Armin Ronacher4f77a302010-07-01 12:15:39 +0200607 if getbool(options, 'newstyle_gettext'):
608 environment.newstyle_gettext = True
609
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200610 source = fileobj.read().decode(options.get('encoding', 'utf-8'))
Armin Ronacherc670b112008-06-29 17:23:04 +0200611 try:
612 node = environment.parse(source)
Armin Ronacher531578d2010-02-06 16:34:54 +0100613 tokens = list(environment.lex(environment.preprocess(source)))
Armin Ronacherc670b112008-06-29 17:23:04 +0200614 except TemplateSyntaxError, e:
Armin Ronacher11619152011-12-15 11:50:27 +0100615 if not silent:
616 raise
Armin Ronacherc670b112008-06-29 17:23:04 +0200617 # skip templates with syntax errors
618 return
Armin Ronacher531578d2010-02-06 16:34:54 +0100619
620 finder = _CommentFinder(tokens, comment_tags)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200621 for lineno, func, message in extract_from_ast(node, keywords):
Armin Ronacher531578d2010-02-06 16:34:54 +0100622 yield lineno, func, message, finder.find_comments(lineno)
Armin Ronachered98cac2008-05-07 08:42:11 +0200623
624
625#: nicer import names
626i18n = InternationalizationExtension
Armin Ronacher5d2733f2008-05-15 23:26:52 +0200627do = ExprStmtExtension
Armin Ronacher3da90312008-05-23 16:37:28 +0200628loopcontrols = LoopControlExtension
Armin Ronacher9b4cc9f2010-02-07 03:55:15 +0100629with_ = WithExtension
Armin Ronacher8346bd72010-03-14 19:43:47 +0100630autoescape = AutoEscapeExtension