blob: 93cde8343a8888cf135f195fcaf8a84337667cee [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 Ronacher4f5008f2008-05-23 23:36:07 +020015from jinja2.defaults import *
Armin Ronacherb5124e62008-04-25 00:36:14 +020016from jinja2.environment import get_spontaneous_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 Ronachered98cac2008-05-07 08:42:11 +020019from jinja2.utils import contextfunction, import_string, Markup
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
60 def __init__(self, environment):
61 self.environment = environment
62
Armin Ronacher7259c762008-04-30 13:03:59 +020063 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
68 return rv
69
Armin Ronacher05530932008-04-20 13:27:49 +020070 def parse(self, parser):
Armin Ronacher023b5e92008-05-08 11:03:10 +020071 """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.
75 """
Armin Ronacher27069d72008-05-11 19:48:12 +020076 raise NotImplementedError()
Armin Ronacher023b5e92008-05-08 11:03:10 +020077
78 def attr(self, name, lineno=None):
79 """Return an attribute node for the current extension. This is useful
Armin Ronacher69e12db2008-05-12 09:00:03 +020080 to pass constants on extensions to generated template code::
Armin Ronacher023b5e92008-05-08 11:03:10 +020081
Armin Ronacher69e12db2008-05-12 09:00:03 +020082 self.attr('_my_attribute', lineno=lineno)
Armin Ronacher023b5e92008-05-08 11:03:10 +020083 """
84 return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
Armin Ronacher05530932008-04-20 13:27:49 +020085
Armin Ronacher27069d72008-05-11 19:48:12 +020086 def call_method(self, name, args=None, kwargs=None, dyn_args=None,
87 dyn_kwargs=None, lineno=None):
Armin Ronacher69e12db2008-05-12 09:00:03 +020088 """Call a method of the extension. This is a shortcut for
89 :meth:`attr` + :class:`jinja2.nodes.Call`.
90 """
Armin Ronacher27069d72008-05-11 19:48:12 +020091 if args is None:
92 args = []
93 if kwargs is None:
94 kwargs = []
95 return nodes.Call(self.attr(name, lineno=lineno), args, kwargs,
96 dyn_args, dyn_kwargs, lineno=lineno)
97
Armin Ronacher05530932008-04-20 13:27:49 +020098
Armin Ronacher5c047ea2008-05-23 22:26:45 +020099@contextfunction
100def _gettext_alias(context, string):
101 return context.resolve('gettext')(string)
102
103
Armin Ronachered98cac2008-05-07 08:42:11 +0200104class InternationalizationExtension(Extension):
Armin Ronacher762079c2008-05-08 23:57:56 +0200105 """This extension adds gettext support to Jinja2."""
Armin Ronacherb5124e62008-04-25 00:36:14 +0200106 tags = set(['trans'])
107
108 def __init__(self, environment):
109 Extension.__init__(self, environment)
Armin Ronacher5c047ea2008-05-23 22:26:45 +0200110 environment.globals['_'] = _gettext_alias
Armin Ronacher762079c2008-05-08 23:57:56 +0200111 environment.extend(
112 install_gettext_translations=self._install,
113 install_null_translations=self._install_null,
114 uninstall_gettext_translations=self._uninstall,
115 extract_translations=self._extract
116 )
117
118 def _install(self, translations):
119 self.environment.globals.update(
120 gettext=translations.ugettext,
121 ngettext=translations.ungettext
122 )
123
124 def _install_null(self):
125 self.environment.globals.update(
126 gettext=lambda x: x,
127 ngettext=lambda s, p, n: (n != 1 and (p,) or (s,))[0]
128 )
129
130 def _uninstall(self, translations):
131 for key in 'gettext', 'ngettext':
132 self.environment.globals.pop(key, None)
133
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)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200138
139 def parse(self, parser):
140 """Parse a translatable tag."""
141 lineno = parser.stream.next().lineno
142
Armin Ronacherb5124e62008-04-25 00:36:14 +0200143 # 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
145 # a later state.
146 plural_expr = None
147 variables = {}
148 while parser.stream.current.type is not 'block_end':
149 if variables:
150 parser.stream.expect('comma')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200151
152 # skip colon for python compatibility
Armin Ronacherfdf95302008-05-11 22:20:51 +0200153 if parser.stream.skip_if('colon'):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200154 break
155
Armin Ronacherb5124e62008-04-25 00:36:14 +0200156 name = parser.stream.expect('name')
157 if name.value in variables:
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200158 parser.fail('translatable variable %r defined twice.' %
159 name.value, name.lineno,
160 exc=TemplateAssertionError)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200161
162 # expressions
163 if parser.stream.current.type is 'assign':
164 parser.stream.next()
165 variables[name.value] = var = parser.parse_expression()
166 else:
167 variables[name.value] = var = nodes.Name(name.value, 'load')
168 if plural_expr is None:
169 plural_expr = var
Armin Ronacher023b5e92008-05-08 11:03:10 +0200170
Armin Ronacherb5124e62008-04-25 00:36:14 +0200171 parser.stream.expect('block_end')
172
173 plural = plural_names = None
174 have_plural = False
175 referenced = set()
176
177 # now parse until endtrans or pluralize
178 singular_names, singular = self._parse_block(parser, True)
179 if singular_names:
180 referenced.update(singular_names)
181 if plural_expr is None:
182 plural_expr = nodes.Name(singular_names[0], 'load')
183
184 # if we have a pluralize block, we parse that too
185 if parser.stream.current.test('name:pluralize'):
186 have_plural = True
187 parser.stream.next()
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)
192 parser.stream.next()
193 referenced.update(plural_names)
194 else:
195 parser.stream.next()
196
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')
201
202 # no variables referenced? no need to escape
203 if not referenced:
204 singular = singular.replace('%%', '%')
205 if plural:
206 plural = plural.replace('%%', '%')
207
208 if not have_plural:
209 plural_expr = None
210 elif plural_expr is None:
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200211 parser.fail('pluralize without variables', lineno)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200212
213 if variables:
214 variables = nodes.Dict([nodes.Pair(nodes.Const(x, lineno=lineno), y)
215 for x, y in variables.items()])
216 else:
217 variables = None
218
219 node = self._make_node(singular, plural, variables, plural_expr)
220 node.set_lineno(lineno)
221 return node
222
223 def _parse_block(self, parser, allow_pluralize):
224 """Parse until the next block tag with a given name."""
225 referenced = []
226 buf = []
227 while 1:
228 if parser.stream.current.type is 'data':
229 buf.append(parser.stream.current.value.replace('%', '%%'))
230 parser.stream.next()
231 elif parser.stream.current.type is 'variable_begin':
232 parser.stream.next()
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':
238 parser.stream.next()
239 if parser.stream.current.test('name:endtrans'):
240 break
241 elif parser.stream.current.test('name:pluralize'):
242 if allow_pluralize:
243 break
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200244 parser.fail('a translatable section can have only one '
245 'pluralize section')
246 parser.fail('control structures in translatable sections are '
247 'not allowed')
Armin Ronacherb5124e62008-04-25 00:36:14 +0200248 else:
249 assert False, 'internal parser error'
250
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200251 return referenced, concat(buf)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200252
253 def _make_node(self, singular, plural, variables, plural_expr):
254 """Generates a useful node from the data provided."""
255 # singular only:
256 if plural_expr is None:
257 gettext = nodes.Name('gettext', 'load')
258 node = nodes.Call(gettext, [nodes.Const(singular)],
259 [], None, None)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200260
261 # singular and plural
262 else:
263 ngettext = nodes.Name('ngettext', 'load')
264 node = nodes.Call(ngettext, [
265 nodes.Const(singular),
266 nodes.Const(plural),
267 plural_expr
268 ], [], None, None)
Armin Ronacherd84ec462008-04-29 13:43:16 +0200269
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)
274
275 if variables:
276 node = nodes.Mod(node, variables)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200277 return nodes.Output([node])
278
279
Armin Ronacher5d2733f2008-05-15 23:26:52 +0200280class 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.
283 """
284 tags = set(['do'])
285
286 def parse(self, parser):
287 node = nodes.ExprStmt(lineno=parser.stream.next().lineno)
288 node.node = parser.parse_tuple()
289 return node
290
291
Armin Ronacher3da90312008-05-23 16:37:28 +0200292class LoopControlExtension(Extension):
293 """Adds break and continue to the template engine."""
294 tags = set(['break', 'continue'])
295
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)
301
302
Armin Ronacherb5124e62008-04-25 00:36:14 +0200303def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS):
304 """Extract localizable strings from the given template node.
305
306 For every string found this function yields a ``(lineno, function,
307 message)`` tuple, where:
308
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).
314 """
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:
318 continue
319
320 strings = []
321 for arg in node.args:
322 if isinstance(arg, nodes.Const) and \
323 isinstance(arg.value, basestring):
324 strings.append(arg.value)
325 else:
326 strings.append(None)
327
328 if len(strings) == 1:
329 strings = strings[0]
330 else:
331 strings = tuple(strings)
332 yield node.lineno, node.node.name, strings
333
334
335def babel_extract(fileobj, keywords, comment_tags, options):
336 """Babel extraction method for Jinja templates.
337
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)
346 """
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200347 extensions = set()
Armin Ronacherb5124e62008-04-25 00:36:14 +0200348 for extension in options.get('extensions', '').split(','):
349 extension = extension.strip()
350 if not extension:
351 continue
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200352 extensions.add(import_string(extension))
353 if InternationalizationExtension not in extensions:
354 extensions.add(InternationalizationExtension)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200355
356 environment = get_spontaneous_environment(
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200357 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),
Armin Ronacherb5124e62008-04-25 00:36:14 +0200367 # fill with defaults so that environments are shared
Armin Ronacher7259c762008-04-30 13:03:59 +0200368 # 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
Armin Ronacherb5124e62008-04-25 00:36:14 +0200372 )
373
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200374 source = fileobj.read().decode(options.get('encoding', 'utf-8'))
375 node = environment.parse(source)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200376 for lineno, func, message in extract_from_ast(node, keywords):
377 yield lineno, func, message, []
Armin Ronachered98cac2008-05-07 08:42:11 +0200378
379
380#: nicer import names
381i18n = InternationalizationExtension
Armin Ronacher5d2733f2008-05-15 23:26:52 +0200382do = ExprStmtExtension
Armin Ronacher3da90312008-05-23 16:37:28 +0200383loopcontrols = LoopControlExtension