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.environment import get_spontaneous_environment
16 from jinja2.runtime import Undefined, concat
17 from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError
18 from jinja2.utils import contextfunction, import_string, Markup
21 # the only real useful gettext functions for a Jinja template. Note
22 # that ugettext must be assigned to gettext as Jinja doesn't support
23 # non unicode strings.
24 GETTEXT_FUNCTIONS = ('_', 'gettext', 'ngettext')
27 class ExtensionRegistry(type):
28 """Gives the extension a unique identifier."""
30 def __new__(cls, name, bases, d):
31 rv = type.__new__(cls, name, bases, d)
32 rv.identifier = rv.__module__ + '.' + rv.__name__
36 class Extension(object):
37 """Extensions can be used to add extra functionality to the Jinja template
38 system at the parser level. Custom extensions are bound to an environment
39 but may not store environment specific data on `self`. The reason for
40 this is that an extension can be bound to another environment (for
41 overlays) by creating a copy and reassigning the `environment` attribute.
43 As extensions are created by the environment they cannot accept any
44 arguments for configuration. One may want to work around that by using
45 a factory function, but that is not possible as extensions are identified
46 by their import name. The correct way to configure the extension is
47 storing the configuration values on the environment. Because this way the
48 environment ends up acting as central configuration storage the
49 attributes may clash which is why extensions have to ensure that the names
50 they choose for configuration are not too generic. ``prefix`` for example
51 is a terrible name, ``fragment_cache_prefix`` on the other hand is a good
52 name as includes the name of the extension (fragment cache).
54 __metaclass__ = ExtensionRegistry
56 #: if this extension parses this is the list of tags it's listening to.
59 def __init__(self, environment):
60 self.environment = environment
62 def bind(self, environment):
63 """Create a copy of this extension bound to another environment."""
64 rv = object.__new__(self.__class__)
65 rv.__dict__.update(self.__dict__)
66 rv.environment = environment
69 def parse(self, parser):
70 """If any of the :attr:`tags` matched this method is called with the
71 parser as first argument. The token the parser stream is pointing at
72 is the name token that matched. This method has to return one or a
73 list of multiple nodes.
75 raise NotImplementedError()
77 def attr(self, name, lineno=None):
78 """Return an attribute node for the current extension. This is useful
79 to pass constants on extensions to generated template code::
81 self.attr('_my_attribute', lineno=lineno)
83 return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
85 def call_method(self, name, args=None, kwargs=None, dyn_args=None,
86 dyn_kwargs=None, lineno=None):
87 """Call a method of the extension. This is a shortcut for
88 :meth:`attr` + :class:`jinja2.nodes.Call`.
94 return nodes.Call(self.attr(name, lineno=lineno), args, kwargs,
95 dyn_args, dyn_kwargs, lineno=lineno)
98 class InternationalizationExtension(Extension):
99 """This extension adds gettext support to Jinja2."""
100 tags = set(['trans'])
102 def __init__(self, environment):
103 Extension.__init__(self, environment)
104 environment.globals['_'] = contextfunction(lambda c, x: c['gettext'](x))
106 install_gettext_translations=self._install,
107 install_null_translations=self._install_null,
108 uninstall_gettext_translations=self._uninstall,
109 extract_translations=self._extract
112 def _install(self, translations):
113 self.environment.globals.update(
114 gettext=translations.ugettext,
115 ngettext=translations.ungettext
118 def _install_null(self):
119 self.environment.globals.update(
121 ngettext=lambda s, p, n: (n != 1 and (p,) or (s,))[0]
124 def _uninstall(self, translations):
125 for key in 'gettext', 'ngettext':
126 self.environment.globals.pop(key, None)
128 def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):
129 if isinstance(source, basestring):
130 source = self.environment.parse(source)
131 return extract_from_ast(source, gettext_functions)
133 def parse(self, parser):
134 """Parse a translatable tag."""
135 lineno = parser.stream.next().lineno
137 # find all the variables referenced. Additionally a variable can be
138 # defined in the body of the trans block too, but this is checked at
142 while parser.stream.current.type is not 'block_end':
144 parser.stream.expect('comma')
146 # skip colon for python compatibility
147 if parser.stream.skip_if('colon'):
150 name = parser.stream.expect('name')
151 if name.value in variables:
152 parser.fail('translatable variable %r defined twice.' %
153 name.value, name.lineno,
154 exc=TemplateAssertionError)
157 if parser.stream.current.type is 'assign':
159 variables[name.value] = var = parser.parse_expression()
161 variables[name.value] = var = nodes.Name(name.value, 'load')
162 if plural_expr is None:
165 parser.stream.expect('block_end')
167 plural = plural_names = None
171 # now parse until endtrans or pluralize
172 singular_names, singular = self._parse_block(parser, True)
174 referenced.update(singular_names)
175 if plural_expr is None:
176 plural_expr = nodes.Name(singular_names[0], 'load')
178 # if we have a pluralize block, we parse that too
179 if parser.stream.current.test('name:pluralize'):
182 if parser.stream.current.type is not 'block_end':
183 plural_expr = parser.parse_expression()
184 parser.stream.expect('block_end')
185 plural_names, plural = self._parse_block(parser, False)
187 referenced.update(plural_names)
191 # register free names as simple name expressions
192 for var in referenced:
193 if var not in variables:
194 variables[var] = nodes.Name(var, 'load')
196 # no variables referenced? no need to escape
198 singular = singular.replace('%%', '%')
200 plural = plural.replace('%%', '%')
204 elif plural_expr is None:
205 parser.fail('pluralize without variables', lineno)
208 variables = nodes.Dict([nodes.Pair(nodes.Const(x, lineno=lineno), y)
209 for x, y in variables.items()])
213 node = self._make_node(singular, plural, variables, plural_expr)
214 node.set_lineno(lineno)
217 def _parse_block(self, parser, allow_pluralize):
218 """Parse until the next block tag with a given name."""
222 if parser.stream.current.type is 'data':
223 buf.append(parser.stream.current.value.replace('%', '%%'))
225 elif parser.stream.current.type is 'variable_begin':
227 name = parser.stream.expect('name').value
228 referenced.append(name)
229 buf.append('%%(%s)s' % name)
230 parser.stream.expect('variable_end')
231 elif parser.stream.current.type is 'block_begin':
233 if parser.stream.current.test('name:endtrans'):
235 elif parser.stream.current.test('name:pluralize'):
238 parser.fail('a translatable section can have only one '
240 parser.fail('control structures in translatable sections are '
243 assert False, 'internal parser error'
245 return referenced, concat(buf)
247 def _make_node(self, singular, plural, variables, plural_expr):
248 """Generates a useful node from the data provided."""
250 if plural_expr is None:
251 gettext = nodes.Name('gettext', 'load')
252 node = nodes.Call(gettext, [nodes.Const(singular)],
255 # singular and plural
257 ngettext = nodes.Name('ngettext', 'load')
258 node = nodes.Call(ngettext, [
259 nodes.Const(singular),
264 # mark the return value as safe if we are in an
265 # environment with autoescaping turned on
266 if self.environment.autoescape:
267 node = nodes.MarkSafe(node)
270 node = nodes.Mod(node, variables)
271 return nodes.Output([node])
274 class ExprStmtExtension(Extension):
275 """Adds a `do` tag to Jinja2 that works like the print statement just
276 that it doesn't print the return value.
280 def parse(self, parser):
281 node = nodes.ExprStmt(lineno=parser.stream.next().lineno)
282 node.node = parser.parse_tuple()
286 def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS):
287 """Extract localizable strings from the given template node.
289 For every string found this function yields a ``(lineno, function,
290 message)`` tuple, where:
292 * ``lineno`` is the number of the line on which the string was found,
293 * ``function`` is the name of the ``gettext`` function used (if the
294 string was extracted from embedded Python code), and
295 * ``message`` is the string itself (a ``unicode`` object, or a tuple
296 of ``unicode`` objects for functions with multiple string arguments).
298 for node in node.find_all(nodes.Call):
299 if not isinstance(node.node, nodes.Name) or \
300 node.node.name not in gettext_functions:
304 for arg in node.args:
305 if isinstance(arg, nodes.Const) and \
306 isinstance(arg.value, basestring):
307 strings.append(arg.value)
311 if len(strings) == 1:
314 strings = tuple(strings)
315 yield node.lineno, node.node.name, strings
318 def babel_extract(fileobj, keywords, comment_tags, options):
319 """Babel extraction method for Jinja templates.
321 :param fileobj: the file-like object the messages should be extracted from
322 :param keywords: a list of keywords (i.e. function names) that should be
323 recognized as translation functions
324 :param comment_tags: a list of translator tags to search for and include
325 in the results. (Unused)
326 :param options: a dictionary of additional options (optional)
327 :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
328 (comments will be empty currently)
330 encoding = options.get('encoding', 'utf-8')
332 have_trans_extension = False
334 for extension in options.get('extensions', '').split(','):
335 extension = extension.strip()
338 extension = import_string(extension)
339 if extension is InternationalizationExtension:
340 have_trans_extension = True
341 extensions.append(extension)
342 if not have_trans_extension:
343 extensions.append(InternationalizationExtension)
345 environment = get_spontaneous_environment(
346 options.get('block_start_string', '{%'),
347 options.get('block_end_string', '%}'),
348 options.get('variable_start_string', '{{'),
349 options.get('variable_end_string', '}}'),
350 options.get('comment_start_string', '{#'),
351 options.get('comment_end_string', '#}'),
352 options.get('line_statement_prefix') or None,
353 options.get('trim_blocks', '').lower() in ('1', 'on', 'yes', 'true'),
355 # fill with defaults so that environments are shared
356 # with other spontaneus environments. The rest of the
357 # arguments are optimizer, undefined, finalize, autoescape,
358 # loader, cache size and auto reloading setting
359 True, Undefined, None, False, None, 0, False
362 node = environment.parse(fileobj.read().decode(encoding))
363 for lineno, func, message in extract_from_ast(node, keywords):
364 yield lineno, func, message, []
367 #: nicer import names
368 i18n = InternationalizationExtension
369 do = ExprStmtExtension