blob: 63e8f5b0cbca543f1f10010d7c35b0b8d30611c3 [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
10 :copyright: Copyright 2008 by Armin Ronacher.
11 :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 Ronacherb5124e62008-04-25 00:36:14 +020015from jinja2.environment import get_spontaneous_environment
Armin Ronacher2feed1d2008-04-26 16:26:52 +020016from jinja2.runtime import Undefined, concat
Benjamin Wieganda3152742008-04-28 18:07:52 +020017from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError
Armin Ronachered98cac2008-05-07 08:42:11 +020018from jinja2.utils import contextfunction, import_string, Markup
Armin Ronacherb5124e62008-04-25 00:36:14 +020019
20
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.
24GETTEXT_FUNCTIONS = ('_', 'gettext', 'ngettext')
Armin Ronacher05530932008-04-20 13:27:49 +020025
26
Armin Ronacher023b5e92008-05-08 11:03:10 +020027class ExtensionRegistry(type):
28 """Gives the extension a unique identifier."""
29
30 def __new__(cls, name, bases, d):
31 rv = type.__new__(cls, name, bases, d)
32 rv.identifier = rv.__module__ + '.' + rv.__name__
33 return rv
34
35
Armin Ronacher05530932008-04-20 13:27:49 +020036class Extension(object):
Armin Ronacher7259c762008-04-30 13:03:59 +020037 """Extensions can be used to add extra functionality to the Jinja template
Armin Ronacher9d42abf2008-05-14 18:10:41 +020038 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.
Armin Ronacher762079c2008-05-08 23:57:56 +020042
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).
Armin Ronacher7259c762008-04-30 13:03:59 +020053 """
Armin Ronacher023b5e92008-05-08 11:03:10 +020054 __metaclass__ = ExtensionRegistry
Armin Ronacher05530932008-04-20 13:27:49 +020055
56 #: if this extension parses this is the list of tags it's listening to.
57 tags = set()
58
59 def __init__(self, environment):
60 self.environment = environment
61
Armin Ronacher7259c762008-04-30 13:03:59 +020062 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
67 return rv
68
Armin Ronacher05530932008-04-20 13:27:49 +020069 def parse(self, parser):
Armin Ronacher023b5e92008-05-08 11:03:10 +020070 """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.
74 """
Armin Ronacher27069d72008-05-11 19:48:12 +020075 raise NotImplementedError()
Armin Ronacher023b5e92008-05-08 11:03:10 +020076
77 def attr(self, name, lineno=None):
78 """Return an attribute node for the current extension. This is useful
Armin Ronacher69e12db2008-05-12 09:00:03 +020079 to pass constants on extensions to generated template code::
Armin Ronacher023b5e92008-05-08 11:03:10 +020080
Armin Ronacher69e12db2008-05-12 09:00:03 +020081 self.attr('_my_attribute', lineno=lineno)
Armin Ronacher023b5e92008-05-08 11:03:10 +020082 """
83 return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
Armin Ronacher05530932008-04-20 13:27:49 +020084
Armin Ronacher27069d72008-05-11 19:48:12 +020085 def call_method(self, name, args=None, kwargs=None, dyn_args=None,
86 dyn_kwargs=None, lineno=None):
Armin Ronacher69e12db2008-05-12 09:00:03 +020087 """Call a method of the extension. This is a shortcut for
88 :meth:`attr` + :class:`jinja2.nodes.Call`.
89 """
Armin Ronacher27069d72008-05-11 19:48:12 +020090 if args is None:
91 args = []
92 if kwargs is None:
93 kwargs = []
94 return nodes.Call(self.attr(name, lineno=lineno), args, kwargs,
95 dyn_args, dyn_kwargs, lineno=lineno)
96
Armin Ronacher05530932008-04-20 13:27:49 +020097
Armin Ronachered98cac2008-05-07 08:42:11 +020098class InternationalizationExtension(Extension):
Armin Ronacher762079c2008-05-08 23:57:56 +020099 """This extension adds gettext support to Jinja2."""
Armin Ronacherb5124e62008-04-25 00:36:14 +0200100 tags = set(['trans'])
101
102 def __init__(self, environment):
103 Extension.__init__(self, environment)
Armin Ronacher762079c2008-05-08 23:57:56 +0200104 environment.globals['_'] = contextfunction(lambda c, x: c['gettext'](x))
105 environment.extend(
106 install_gettext_translations=self._install,
107 install_null_translations=self._install_null,
108 uninstall_gettext_translations=self._uninstall,
109 extract_translations=self._extract
110 )
111
112 def _install(self, translations):
113 self.environment.globals.update(
114 gettext=translations.ugettext,
115 ngettext=translations.ungettext
116 )
117
118 def _install_null(self):
119 self.environment.globals.update(
120 gettext=lambda x: x,
121 ngettext=lambda s, p, n: (n != 1 and (p,) or (s,))[0]
122 )
123
124 def _uninstall(self, translations):
125 for key in 'gettext', 'ngettext':
126 self.environment.globals.pop(key, None)
127
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)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200132
133 def parse(self, parser):
134 """Parse a translatable tag."""
135 lineno = parser.stream.next().lineno
136
Armin Ronacherb5124e62008-04-25 00:36:14 +0200137 # 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
139 # a later state.
140 plural_expr = None
141 variables = {}
142 while parser.stream.current.type is not 'block_end':
143 if variables:
144 parser.stream.expect('comma')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200145
146 # skip colon for python compatibility
Armin Ronacherfdf95302008-05-11 22:20:51 +0200147 if parser.stream.skip_if('colon'):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200148 break
149
Armin Ronacherb5124e62008-04-25 00:36:14 +0200150 name = parser.stream.expect('name')
151 if name.value in variables:
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200152 parser.fail('translatable variable %r defined twice.' %
153 name.value, name.lineno,
154 exc=TemplateAssertionError)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200155
156 # expressions
157 if parser.stream.current.type is 'assign':
158 parser.stream.next()
159 variables[name.value] = var = parser.parse_expression()
160 else:
161 variables[name.value] = var = nodes.Name(name.value, 'load')
162 if plural_expr is None:
163 plural_expr = var
Armin Ronacher023b5e92008-05-08 11:03:10 +0200164
Armin Ronacherb5124e62008-04-25 00:36:14 +0200165 parser.stream.expect('block_end')
166
167 plural = plural_names = None
168 have_plural = False
169 referenced = set()
170
171 # now parse until endtrans or pluralize
172 singular_names, singular = self._parse_block(parser, True)
173 if singular_names:
174 referenced.update(singular_names)
175 if plural_expr is None:
176 plural_expr = nodes.Name(singular_names[0], 'load')
177
178 # if we have a pluralize block, we parse that too
179 if parser.stream.current.test('name:pluralize'):
180 have_plural = True
181 parser.stream.next()
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)
186 parser.stream.next()
187 referenced.update(plural_names)
188 else:
189 parser.stream.next()
190
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')
195
196 # no variables referenced? no need to escape
197 if not referenced:
198 singular = singular.replace('%%', '%')
199 if plural:
200 plural = plural.replace('%%', '%')
201
202 if not have_plural:
203 plural_expr = None
204 elif plural_expr is None:
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200205 parser.fail('pluralize without variables', lineno)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200206
207 if variables:
208 variables = nodes.Dict([nodes.Pair(nodes.Const(x, lineno=lineno), y)
209 for x, y in variables.items()])
210 else:
211 variables = None
212
213 node = self._make_node(singular, plural, variables, plural_expr)
214 node.set_lineno(lineno)
215 return node
216
217 def _parse_block(self, parser, allow_pluralize):
218 """Parse until the next block tag with a given name."""
219 referenced = []
220 buf = []
221 while 1:
222 if parser.stream.current.type is 'data':
223 buf.append(parser.stream.current.value.replace('%', '%%'))
224 parser.stream.next()
225 elif parser.stream.current.type is 'variable_begin':
226 parser.stream.next()
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':
232 parser.stream.next()
233 if parser.stream.current.test('name:endtrans'):
234 break
235 elif parser.stream.current.test('name:pluralize'):
236 if allow_pluralize:
237 break
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200238 parser.fail('a translatable section can have only one '
239 'pluralize section')
240 parser.fail('control structures in translatable sections are '
241 'not allowed')
Armin Ronacherb5124e62008-04-25 00:36:14 +0200242 else:
243 assert False, 'internal parser error'
244
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200245 return referenced, concat(buf)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200246
247 def _make_node(self, singular, plural, variables, plural_expr):
248 """Generates a useful node from the data provided."""
249 # singular only:
250 if plural_expr is None:
251 gettext = nodes.Name('gettext', 'load')
252 node = nodes.Call(gettext, [nodes.Const(singular)],
253 [], None, None)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200254
255 # singular and plural
256 else:
257 ngettext = nodes.Name('ngettext', 'load')
258 node = nodes.Call(ngettext, [
259 nodes.Const(singular),
260 nodes.Const(plural),
261 plural_expr
262 ], [], None, None)
Armin Ronacherd84ec462008-04-29 13:43:16 +0200263
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)
268
269 if variables:
270 node = nodes.Mod(node, variables)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200271 return nodes.Output([node])
272
273
Armin Ronacher5d2733f2008-05-15 23:26:52 +0200274class 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.
277 """
278 tags = set(['do'])
279
280 def parse(self, parser):
281 node = nodes.ExprStmt(lineno=parser.stream.next().lineno)
282 node.node = parser.parse_tuple()
283 return node
284
285
Armin Ronacher3da90312008-05-23 16:37:28 +0200286class LoopControlExtension(Extension):
287 """Adds break and continue to the template engine."""
288 tags = set(['break', 'continue'])
289
290 def parse(self, parser):
291 token = parser.stream.next()
292 if token.value == 'break':
293 return nodes.Break(lineno=token.lineno)
294 return nodes.Continue(lineno=token.lineno)
295
296
Armin Ronacherb5124e62008-04-25 00:36:14 +0200297def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS):
298 """Extract localizable strings from the given template node.
299
300 For every string found this function yields a ``(lineno, function,
301 message)`` tuple, where:
302
303 * ``lineno`` is the number of the line on which the string was found,
304 * ``function`` is the name of the ``gettext`` function used (if the
305 string was extracted from embedded Python code), and
306 * ``message`` is the string itself (a ``unicode`` object, or a tuple
307 of ``unicode`` objects for functions with multiple string arguments).
308 """
309 for node in node.find_all(nodes.Call):
310 if not isinstance(node.node, nodes.Name) or \
311 node.node.name not in gettext_functions:
312 continue
313
314 strings = []
315 for arg in node.args:
316 if isinstance(arg, nodes.Const) and \
317 isinstance(arg.value, basestring):
318 strings.append(arg.value)
319 else:
320 strings.append(None)
321
322 if len(strings) == 1:
323 strings = strings[0]
324 else:
325 strings = tuple(strings)
326 yield node.lineno, node.node.name, strings
327
328
329def babel_extract(fileobj, keywords, comment_tags, options):
330 """Babel extraction method for Jinja templates.
331
332 :param fileobj: the file-like object the messages should be extracted from
333 :param keywords: a list of keywords (i.e. function names) that should be
334 recognized as translation functions
335 :param comment_tags: a list of translator tags to search for and include
336 in the results. (Unused)
337 :param options: a dictionary of additional options (optional)
338 :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
339 (comments will be empty currently)
340 """
341 encoding = options.get('encoding', 'utf-8')
342
343 have_trans_extension = False
344 extensions = []
345 for extension in options.get('extensions', '').split(','):
346 extension = extension.strip()
347 if not extension:
348 continue
349 extension = import_string(extension)
Armin Ronachered98cac2008-05-07 08:42:11 +0200350 if extension is InternationalizationExtension:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200351 have_trans_extension = True
352 extensions.append(extension)
353 if not have_trans_extension:
Armin Ronachered98cac2008-05-07 08:42:11 +0200354 extensions.append(InternationalizationExtension)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200355
356 environment = get_spontaneous_environment(
357 options.get('block_start_string', '{%'),
358 options.get('block_end_string', '%}'),
359 options.get('variable_start_string', '{{'),
360 options.get('variable_end_string', '}}'),
361 options.get('comment_start_string', '{#'),
362 options.get('comment_end_string', '#}'),
363 options.get('line_statement_prefix') or None,
364 options.get('trim_blocks', '').lower() in ('1', 'on', 'yes', 'true'),
365 tuple(extensions),
366 # fill with defaults so that environments are shared
Armin Ronacher7259c762008-04-30 13:03:59 +0200367 # with other spontaneus environments. The rest of the
368 # arguments are optimizer, undefined, finalize, autoescape,
369 # loader, cache size and auto reloading setting
370 True, Undefined, None, False, None, 0, False
Armin Ronacherb5124e62008-04-25 00:36:14 +0200371 )
372
373 node = environment.parse(fileobj.read().decode(encoding))
374 for lineno, func, message in extract_from_ast(node, keywords):
375 yield lineno, func, message, []
Armin Ronachered98cac2008-05-07 08:42:11 +0200376
377
378#: nicer import names
379i18n = InternationalizationExtension
Armin Ronacher5d2733f2008-05-15 23:26:52 +0200380do = ExprStmtExtension
Armin Ronacher3da90312008-05-23 16:37:28 +0200381loopcontrols = LoopControlExtension