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 parse(self, parser):
71 """If any of the :attr:`tags` matched this method is called with the
72 parser as first argument. The token the parser stream is pointing at
73 is the name token that matched. This method has to return one or a
74 list of multiple nodes.
76 raise NotImplementedError()
78 def attr(self, name, lineno=None):
79 """Return an attribute node for the current extension. This is useful
80 to pass constants on extensions to generated template code::
82 self.attr('_my_attribute', lineno=lineno)
84 return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
86 def call_method(self, name, args=None, kwargs=None, dyn_args=None,
87 dyn_kwargs=None, lineno=None):
88 """Call a method of the extension. This is a shortcut for
89 :meth:`attr` + :class:`jinja2.nodes.Call`.
95 return nodes.Call(self.attr(name, lineno=lineno), args, kwargs,
96 dyn_args, dyn_kwargs, lineno=lineno)
100 def _gettext_alias(context, string):
101 return context.resolve('gettext')(string)
104 class InternationalizationExtension(Extension):
105 """This extension adds gettext support to Jinja2."""
106 tags = set(['trans'])
108 def __init__(self, environment):
109 Extension.__init__(self, environment)
110 environment.globals['_'] = _gettext_alias
112 install_gettext_translations=self._install,
113 install_null_translations=self._install_null,
114 uninstall_gettext_translations=self._uninstall,
115 extract_translations=self._extract
118 def _install(self, translations):
119 self.environment.globals.update(
120 gettext=translations.ugettext,
121 ngettext=translations.ungettext
124 def _install_null(self):
125 self.environment.globals.update(
127 ngettext=lambda s, p, n: (n != 1 and (p,) or (s,))[0]
130 def _uninstall(self, translations):
131 for key in 'gettext', 'ngettext':
132 self.environment.globals.pop(key, None)
134 def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):
135 if isinstance(source, basestring):
136 source = self.environment.parse(source)
137 return extract_from_ast(source, gettext_functions)
139 def parse(self, parser):
140 """Parse a translatable tag."""
141 lineno = parser.stream.next().lineno
143 # find all the variables referenced. Additionally a variable can be
144 # defined in the body of the trans block too, but this is checked at
148 while parser.stream.current.type is not 'block_end':
150 parser.stream.expect('comma')
152 # skip colon for python compatibility
153 if parser.stream.skip_if('colon'):
156 name = parser.stream.expect('name')
157 if name.value in variables:
158 parser.fail('translatable variable %r defined twice.' %
159 name.value, name.lineno,
160 exc=TemplateAssertionError)
163 if parser.stream.current.type is 'assign':
165 variables[name.value] = var = parser.parse_expression()
167 variables[name.value] = var = nodes.Name(name.value, 'load')
168 if plural_expr is None:
171 parser.stream.expect('block_end')
173 plural = plural_names = None
177 # now parse until endtrans or pluralize
178 singular_names, singular = self._parse_block(parser, True)
180 referenced.update(singular_names)
181 if plural_expr is None:
182 plural_expr = nodes.Name(singular_names[0], 'load')
184 # if we have a pluralize block, we parse that too
185 if parser.stream.current.test('name:pluralize'):
188 if parser.stream.current.type is not 'block_end':
189 plural_expr = parser.parse_expression()
190 parser.stream.expect('block_end')
191 plural_names, plural = self._parse_block(parser, False)
193 referenced.update(plural_names)
197 # register free names as simple name expressions
198 for var in referenced:
199 if var not in variables:
200 variables[var] = nodes.Name(var, 'load')
202 # no variables referenced? no need to escape
204 singular = singular.replace('%%', '%')
206 plural = plural.replace('%%', '%')
210 elif plural_expr is None:
211 parser.fail('pluralize without variables', lineno)
214 variables = nodes.Dict([nodes.Pair(nodes.Const(x, lineno=lineno), y)
215 for x, y in variables.items()])
219 node = self._make_node(singular, plural, variables, plural_expr)
220 node.set_lineno(lineno)
223 def _parse_block(self, parser, allow_pluralize):
224 """Parse until the next block tag with a given name."""
228 if parser.stream.current.type is 'data':
229 buf.append(parser.stream.current.value.replace('%', '%%'))
231 elif parser.stream.current.type is 'variable_begin':
233 name = parser.stream.expect('name').value
234 referenced.append(name)
235 buf.append('%%(%s)s' % name)
236 parser.stream.expect('variable_end')
237 elif parser.stream.current.type is 'block_begin':
239 if parser.stream.current.test('name:endtrans'):
241 elif parser.stream.current.test('name:pluralize'):
244 parser.fail('a translatable section can have only one '
246 parser.fail('control structures in translatable sections are '
249 assert False, 'internal parser error'
251 return referenced, concat(buf)
253 def _make_node(self, singular, plural, variables, plural_expr):
254 """Generates a useful node from the data provided."""
256 if plural_expr is None:
257 gettext = nodes.Name('gettext', 'load')
258 node = nodes.Call(gettext, [nodes.Const(singular)],
261 # singular and plural
263 ngettext = nodes.Name('ngettext', 'load')
264 node = nodes.Call(ngettext, [
265 nodes.Const(singular),
270 # mark the return value as safe if we are in an
271 # environment with autoescaping turned on
272 if self.environment.autoescape:
273 node = nodes.MarkSafe(node)
276 node = nodes.Mod(node, variables)
277 return nodes.Output([node])
280 class ExprStmtExtension(Extension):
281 """Adds a `do` tag to Jinja2 that works like the print statement just
282 that it doesn't print the return value.
286 def parse(self, parser):
287 node = nodes.ExprStmt(lineno=parser.stream.next().lineno)
288 node.node = parser.parse_tuple()
292 class LoopControlExtension(Extension):
293 """Adds break and continue to the template engine."""
294 tags = set(['break', 'continue'])
296 def parse(self, parser):
297 token = parser.stream.next()
298 if token.value == 'break':
299 return nodes.Break(lineno=token.lineno)
300 return nodes.Continue(lineno=token.lineno)
303 def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS):
304 """Extract localizable strings from the given template node.
306 For every string found this function yields a ``(lineno, function,
307 message)`` tuple, where:
309 * ``lineno`` is the number of the line on which the string was found,
310 * ``function`` is the name of the ``gettext`` function used (if the
311 string was extracted from embedded Python code), and
312 * ``message`` is the string itself (a ``unicode`` object, or a tuple
313 of ``unicode`` objects for functions with multiple string arguments).
315 for node in node.find_all(nodes.Call):
316 if not isinstance(node.node, nodes.Name) or \
317 node.node.name not in gettext_functions:
321 for arg in node.args:
322 if isinstance(arg, nodes.Const) and \
323 isinstance(arg.value, basestring):
324 strings.append(arg.value)
328 if len(strings) == 1:
331 strings = tuple(strings)
332 yield node.lineno, node.node.name, strings
335 def babel_extract(fileobj, keywords, comment_tags, options):
336 """Babel extraction method for Jinja templates.
338 :param fileobj: the file-like object the messages should be extracted from
339 :param keywords: a list of keywords (i.e. function names) that should be
340 recognized as translation functions
341 :param comment_tags: a list of translator tags to search for and include
342 in the results. (Unused)
343 :param options: a dictionary of additional options (optional)
344 :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
345 (comments will be empty currently)
348 for extension in options.get('extensions', '').split(','):
349 extension = extension.strip()
352 extensions.add(import_string(extension))
353 if InternationalizationExtension not in extensions:
354 extensions.add(InternationalizationExtension)
356 environment = get_spontaneous_environment(
357 options.get('block_start_string', BLOCK_START_STRING),
358 options.get('block_end_string', BLOCK_END_STRING),
359 options.get('variable_start_string', VARIABLE_START_STRING),
360 options.get('variable_end_string', VARIABLE_END_STRING),
361 options.get('comment_start_string', COMMENT_START_STRING),
362 options.get('comment_end_string', COMMENT_END_STRING),
363 options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,
364 str(options.get('trim_blocks', TRIM_BLOCKS)).lower() in \
365 ('1', 'on', 'yes', 'true'),
366 NEWLINE_SEQUENCE, frozenset(extensions),
367 # fill with defaults so that environments are shared
368 # with other spontaneus environments. The rest of the
369 # arguments are optimizer, undefined, finalize, autoescape,
370 # loader, cache size and auto reloading setting
371 True, Undefined, None, False, None, 0, False
374 source = fileobj.read().decode(options.get('encoding', 'utf-8'))
375 node = environment.parse(source)
376 for lineno, func, message in extract_from_ast(node, keywords):
377 yield lineno, func, message, []
380 #: nicer import names
381 i18n = InternationalizationExtension
382 do = ExprStmtExtension
383 loopcontrols = LoopControlExtension