1 # -*- coding: utf-8 -*-
6 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
10 :copyright: Copyright 2008 by Armin Ronacher.
13 from collections import deque
14 from jinja2 import nodes
15 from jinja2.defaults import *
16 from jinja2.environment import get_spontaneous_environment
17 from jinja2.runtime import Undefined, concat
18 from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError
19 from jinja2.utils import contextfunction, import_string, Markup
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.
25 GETTEXT_FUNCTIONS = ('_', 'gettext', 'ngettext')
28 class ExtensionRegistry(type):
29 """Gives the extension an unique identifier."""
31 def __new__(cls, name, bases, d):
32 rv = type.__new__(cls, name, bases, d)
33 rv.identifier = rv.__module__ + '.' + rv.__name__
37 class Extension(object):
38 """Extensions can be used to add extra functionality to the Jinja template
39 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.
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).
55 __metaclass__ = ExtensionRegistry
57 #: if this extension parses this is the list of tags it's listening to.
60 def __init__(self, environment):
61 self.environment = environment
63 def bind(self, environment):
64 """Create a copy of this extension bound to another environment."""
65 rv = object.__new__(self.__class__)
66 rv.__dict__.update(self.__dict__)
67 rv.environment = environment
70 def preprocess(self, source, name, filename=None):
71 """This method is called before the actual lexing and can be used to
72 preprocess the source. The `filename` is optional. The return value
73 must be the preprocessed source.
77 def filter_stream(self, stream):
78 """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used
79 to filter tokens returned. This method has to return an iterable of
80 :class:`~jinja2.lexer.Token`\s, but it doesn't have to return a
81 :class:`~jinja2.lexer.TokenStream`.
83 In the `ext` folder of the Jinja2 source distribution there is a file
84 called `inlinegettext.py` which implements a filter that utilizes this
89 def parse(self, parser):
90 """If any of the :attr:`tags` matched this method is called with the
91 parser as first argument. The token the parser stream is pointing at
92 is the name token that matched. This method has to return one or a
93 list of multiple nodes.
95 raise NotImplementedError()
97 def attr(self, name, lineno=None):
98 """Return an attribute node for the current extension. This is useful
99 to pass constants on extensions to generated template code::
101 self.attr('_my_attribute', lineno=lineno)
103 return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
105 def call_method(self, name, args=None, kwargs=None, dyn_args=None,
106 dyn_kwargs=None, lineno=None):
107 """Call a method of the extension. This is a shortcut for
108 :meth:`attr` + :class:`jinja2.nodes.Call`.
114 return nodes.Call(self.attr(name, lineno=lineno), args, kwargs,
115 dyn_args, dyn_kwargs, lineno=lineno)
119 def _gettext_alias(context, string):
120 return context.resolve('gettext')(string)
123 class InternationalizationExtension(Extension):
124 """This extension adds gettext support to Jinja2."""
125 tags = set(['trans'])
127 # TODO: the i18n extension is currently reevaluating values in a few
128 # situations. Take this example:
129 # {% trans count=something() %}{{ count }} foo{% pluralize
130 # %}{{ count }} fooss{% endtrans %}
131 # something is called twice here. One time for the gettext value and
132 # the other time for the n-parameter of the ngettext function.
134 def __init__(self, environment):
135 Extension.__init__(self, environment)
136 environment.globals['_'] = _gettext_alias
138 install_gettext_translations=self._install,
139 install_null_translations=self._install_null,
140 uninstall_gettext_translations=self._uninstall,
141 extract_translations=self._extract
144 def _install(self, translations):
145 gettext = getattr(translations, 'ugettext', None)
147 gettext = translations.gettext
148 ngettext = getattr(translations, 'ungettext', None)
150 ngettext = translations.ngettext
151 self.environment.globals.update(gettext=gettext, ngettext=ngettext)
153 def _install_null(self):
154 self.environment.globals.update(
156 ngettext=lambda s, p, n: (n != 1 and (p,) or (s,))[0]
159 def _uninstall(self, translations):
160 for key in 'gettext', 'ngettext':
161 self.environment.globals.pop(key, None)
163 def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):
164 if isinstance(source, basestring):
165 source = self.environment.parse(source)
166 return extract_from_ast(source, gettext_functions)
168 def parse(self, parser):
169 """Parse a translatable tag."""
170 lineno = parser.stream.next().lineno
172 # find all the variables referenced. Additionally a variable can be
173 # defined in the body of the trans block too, but this is checked at
177 while parser.stream.current.type is not 'block_end':
179 parser.stream.expect('comma')
181 # skip colon for python compatibility
182 if parser.stream.skip_if('colon'):
185 name = parser.stream.expect('name')
186 if name.value in variables:
187 parser.fail('translatable variable %r defined twice.' %
188 name.value, name.lineno,
189 exc=TemplateAssertionError)
192 if parser.stream.current.type is 'assign':
194 variables[name.value] = var = parser.parse_expression()
196 variables[name.value] = var = nodes.Name(name.value, 'load')
197 if plural_expr is None:
200 parser.stream.expect('block_end')
202 plural = plural_names = None
206 # now parse until endtrans or pluralize
207 singular_names, singular = self._parse_block(parser, True)
209 referenced.update(singular_names)
210 if plural_expr is None:
211 plural_expr = nodes.Name(singular_names[0], 'load')
213 # if we have a pluralize block, we parse that too
214 if parser.stream.current.test('name:pluralize'):
217 if parser.stream.current.type is not 'block_end':
218 name = parser.stream.expect('name')
219 if name.value not in variables:
220 parser.fail('unknown variable %r for pluralization' %
221 name.value, name.lineno,
222 exc=TemplateAssertionError)
223 plural_expr = variables[name.value]
224 parser.stream.expect('block_end')
225 plural_names, plural = self._parse_block(parser, False)
227 referenced.update(plural_names)
231 # register free names as simple name expressions
232 for var in referenced:
233 if var not in variables:
234 variables[var] = nodes.Name(var, 'load')
236 # no variables referenced? no need to escape
238 singular = singular.replace('%%', '%')
240 plural = plural.replace('%%', '%')
244 elif plural_expr is None:
245 parser.fail('pluralize without variables', lineno)
248 variables = nodes.Dict([nodes.Pair(nodes.Const(x, lineno=lineno), y)
249 for x, y in variables.items()])
253 node = self._make_node(singular, plural, variables, plural_expr)
254 node.set_lineno(lineno)
257 def _parse_block(self, parser, allow_pluralize):
258 """Parse until the next block tag with a given name."""
262 if parser.stream.current.type is 'data':
263 buf.append(parser.stream.current.value.replace('%', '%%'))
265 elif parser.stream.current.type is 'variable_begin':
267 name = parser.stream.expect('name').value
268 referenced.append(name)
269 buf.append('%%(%s)s' % name)
270 parser.stream.expect('variable_end')
271 elif parser.stream.current.type is 'block_begin':
273 if parser.stream.current.test('name:endtrans'):
275 elif parser.stream.current.test('name:pluralize'):
278 parser.fail('a translatable section can have only one '
280 parser.fail('control structures in translatable sections are '
282 elif parser.stream.eos:
283 parser.fail('unclosed translation block')
285 assert False, 'internal parser error'
287 return referenced, concat(buf)
289 def _make_node(self, singular, plural, variables, plural_expr):
290 """Generates a useful node from the data provided."""
292 if plural_expr is None:
293 gettext = nodes.Name('gettext', 'load')
294 node = nodes.Call(gettext, [nodes.Const(singular)],
297 # singular and plural
299 ngettext = nodes.Name('ngettext', 'load')
300 node = nodes.Call(ngettext, [
301 nodes.Const(singular),
306 # mark the return value as safe if we are in an
307 # environment with autoescaping turned on
308 if self.environment.autoescape:
309 node = nodes.MarkSafe(node)
312 node = nodes.Mod(node, variables)
313 return nodes.Output([node])
316 class ExprStmtExtension(Extension):
317 """Adds a `do` tag to Jinja2 that works like the print statement just
318 that it doesn't print the return value.
322 def parse(self, parser):
323 node = nodes.ExprStmt(lineno=parser.stream.next().lineno)
324 node.node = parser.parse_tuple()
328 class LoopControlExtension(Extension):
329 """Adds break and continue to the template engine."""
330 tags = set(['break', 'continue'])
332 def parse(self, parser):
333 token = parser.stream.next()
334 if token.value == 'break':
335 return nodes.Break(lineno=token.lineno)
336 return nodes.Continue(lineno=token.lineno)
339 def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS,
341 """Extract localizable strings from the given template node. Per
342 default this function returns matches in babel style that means non string
343 parameters as well as keyword arguments are returned as `None`. This
344 allows Babel to figure out what you really meant if you are using
345 gettext functions that allow keyword arguments for placeholder expansion.
346 If you don't want that behavior set the `babel_style` parameter to `False`
347 which causes only strings to be returned and parameters are always stored
348 in tuples. As a consequence invalid gettext calls (calls without a single
349 string parameter or string parameters after non-string parameters) are
352 This example explains the behavior:
354 >>> from jinja2 import Environment
355 >>> env = Environment()
356 >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')
357 >>> list(extract_from_ast(node))
358 [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]
359 >>> list(extract_from_ast(node, babel_style=False))
360 [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]
362 For every string found this function yields a ``(lineno, function,
363 message)`` tuple, where:
365 * ``lineno`` is the number of the line on which the string was found,
366 * ``function`` is the name of the ``gettext`` function used (if the
367 string was extracted from embedded Python code), and
368 * ``message`` is the string itself (a ``unicode`` object, or a tuple
369 of ``unicode`` objects for functions with multiple string arguments).
371 for node in node.find_all(nodes.Call):
372 if not isinstance(node.node, nodes.Name) or \
373 node.node.name not in gettext_functions:
377 for arg in node.args:
378 if isinstance(arg, nodes.Const) and \
379 isinstance(arg.value, basestring):
380 strings.append(arg.value)
384 for arg in node.kwargs:
386 if node.dyn_args is not None:
388 if node.dyn_kwargs is not None:
392 strings = tuple(x for x in strings if x is not None)
396 if len(strings) == 1:
399 strings = tuple(strings)
400 yield node.lineno, node.node.name, strings
403 def babel_extract(fileobj, keywords, comment_tags, options):
404 """Babel extraction method for Jinja templates.
406 :param fileobj: the file-like object the messages should be extracted from
407 :param keywords: a list of keywords (i.e. function names) that should be
408 recognized as translation functions
409 :param comment_tags: a list of translator tags to search for and include
410 in the results. (Unused)
411 :param options: a dictionary of additional options (optional)
412 :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
413 (comments will be empty currently)
416 for extension in options.get('extensions', '').split(','):
417 extension = extension.strip()
420 extensions.add(import_string(extension))
421 if InternationalizationExtension not in extensions:
422 extensions.add(InternationalizationExtension)
424 environment = get_spontaneous_environment(
425 options.get('block_start_string', BLOCK_START_STRING),
426 options.get('block_end_string', BLOCK_END_STRING),
427 options.get('variable_start_string', VARIABLE_START_STRING),
428 options.get('variable_end_string', VARIABLE_END_STRING),
429 options.get('comment_start_string', COMMENT_START_STRING),
430 options.get('comment_end_string', COMMENT_END_STRING),
431 options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,
432 str(options.get('trim_blocks', TRIM_BLOCKS)).lower() in \
433 ('1', 'on', 'yes', 'true'),
434 NEWLINE_SEQUENCE, frozenset(extensions),
435 # fill with defaults so that environments are shared
436 # with other spontaneus environments. The rest of the
437 # arguments are optimizer, undefined, finalize, autoescape,
438 # loader, cache size, auto reloading setting and the
440 True, Undefined, None, False, None, 0, False, None
443 source = fileobj.read().decode(options.get('encoding', 'utf-8'))
445 node = environment.parse(source)
446 except TemplateSyntaxError, e:
447 # skip templates with syntax errors
449 for lineno, func, message in extract_from_ast(node, keywords):
450 yield lineno, func, message, []
453 #: nicer import names
454 i18n = InternationalizationExtension
455 do = ExprStmtExtension
456 loopcontrols = LoopControlExtension