ext.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. # -*- coding: utf-8 -*-
  2. """
  3. jinja2.ext
  4. ~~~~~~~~~~
  5. Jinja extensions allow to add custom tags similar to the way django custom
  6. tags work. By default two example extensions exist: an i18n and a cache
  7. extension.
  8. :copyright: (c) 2010 by the Jinja Team.
  9. :license: BSD.
  10. """
  11. from jinja2 import nodes
  12. from jinja2.defaults import BLOCK_START_STRING, \
  13. BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \
  14. COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \
  15. LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE, \
  16. KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS
  17. from jinja2.environment import Environment
  18. from jinja2.runtime import concat
  19. from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError
  20. from jinja2.utils import contextfunction, import_string, Markup
  21. from jinja2._compat import with_metaclass, string_types, iteritems
  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')
  26. class ExtensionRegistry(type):
  27. """Gives the extension an unique identifier."""
  28. def __new__(cls, name, bases, d):
  29. rv = type.__new__(cls, name, bases, d)
  30. rv.identifier = rv.__module__ + '.' + rv.__name__
  31. return rv
  32. class Extension(with_metaclass(ExtensionRegistry, object)):
  33. """Extensions can be used to add extra functionality to the Jinja template
  34. system at the parser level. Custom extensions are bound to an environment
  35. but may not store environment specific data on `self`. The reason for
  36. this is that an extension can be bound to another environment (for
  37. overlays) by creating a copy and reassigning the `environment` attribute.
  38. As extensions are created by the environment they cannot accept any
  39. arguments for configuration. One may want to work around that by using
  40. a factory function, but that is not possible as extensions are identified
  41. by their import name. The correct way to configure the extension is
  42. storing the configuration values on the environment. Because this way the
  43. environment ends up acting as central configuration storage the
  44. attributes may clash which is why extensions have to ensure that the names
  45. they choose for configuration are not too generic. ``prefix`` for example
  46. is a terrible name, ``fragment_cache_prefix`` on the other hand is a good
  47. name as includes the name of the extension (fragment cache).
  48. """
  49. #: if this extension parses this is the list of tags it's listening to.
  50. tags = set()
  51. #: the priority of that extension. This is especially useful for
  52. #: extensions that preprocess values. A lower value means higher
  53. #: priority.
  54. #:
  55. #: .. versionadded:: 2.4
  56. priority = 100
  57. def __init__(self, environment):
  58. self.environment = environment
  59. def bind(self, environment):
  60. """Create a copy of this extension bound to another environment."""
  61. rv = object.__new__(self.__class__)
  62. rv.__dict__.update(self.__dict__)
  63. rv.environment = environment
  64. return rv
  65. def preprocess(self, source, name, filename=None):
  66. """This method is called before the actual lexing and can be used to
  67. preprocess the source. The `filename` is optional. The return value
  68. must be the preprocessed source.
  69. """
  70. return source
  71. def filter_stream(self, stream):
  72. """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used
  73. to filter tokens returned. This method has to return an iterable of
  74. :class:`~jinja2.lexer.Token`\s, but it doesn't have to return a
  75. :class:`~jinja2.lexer.TokenStream`.
  76. In the `ext` folder of the Jinja2 source distribution there is a file
  77. called `inlinegettext.py` which implements a filter that utilizes this
  78. method.
  79. """
  80. return stream
  81. def parse(self, parser):
  82. """If any of the :attr:`tags` matched this method is called with the
  83. parser as first argument. The token the parser stream is pointing at
  84. is the name token that matched. This method has to return one or a
  85. list of multiple nodes.
  86. """
  87. raise NotImplementedError()
  88. def attr(self, name, lineno=None):
  89. """Return an attribute node for the current extension. This is useful
  90. to pass constants on extensions to generated template code.
  91. ::
  92. self.attr('_my_attribute', lineno=lineno)
  93. """
  94. return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
  95. def call_method(self, name, args=None, kwargs=None, dyn_args=None,
  96. dyn_kwargs=None, lineno=None):
  97. """Call a method of the extension. This is a shortcut for
  98. :meth:`attr` + :class:`jinja2.nodes.Call`.
  99. """
  100. if args is None:
  101. args = []
  102. if kwargs is None:
  103. kwargs = []
  104. return nodes.Call(self.attr(name, lineno=lineno), args, kwargs,
  105. dyn_args, dyn_kwargs, lineno=lineno)
  106. @contextfunction
  107. def _gettext_alias(__context, *args, **kwargs):
  108. return __context.call(__context.resolve('gettext'), *args, **kwargs)
  109. def _make_new_gettext(func):
  110. @contextfunction
  111. def gettext(__context, __string, **variables):
  112. rv = __context.call(func, __string)
  113. if __context.eval_ctx.autoescape:
  114. rv = Markup(rv)
  115. return rv % variables
  116. return gettext
  117. def _make_new_ngettext(func):
  118. @contextfunction
  119. def ngettext(__context, __singular, __plural, __num, **variables):
  120. variables.setdefault('num', __num)
  121. rv = __context.call(func, __singular, __plural, __num)
  122. if __context.eval_ctx.autoescape:
  123. rv = Markup(rv)
  124. return rv % variables
  125. return ngettext
  126. class InternationalizationExtension(Extension):
  127. """This extension adds gettext support to Jinja2."""
  128. tags = set(['trans'])
  129. # TODO: the i18n extension is currently reevaluating values in a few
  130. # situations. Take this example:
  131. # {% trans count=something() %}{{ count }} foo{% pluralize
  132. # %}{{ count }} fooss{% endtrans %}
  133. # something is called twice here. One time for the gettext value and
  134. # the other time for the n-parameter of the ngettext function.
  135. def __init__(self, environment):
  136. Extension.__init__(self, environment)
  137. environment.globals['_'] = _gettext_alias
  138. environment.extend(
  139. install_gettext_translations=self._install,
  140. install_null_translations=self._install_null,
  141. install_gettext_callables=self._install_callables,
  142. uninstall_gettext_translations=self._uninstall,
  143. extract_translations=self._extract,
  144. newstyle_gettext=False
  145. )
  146. def _install(self, translations, newstyle=None):
  147. gettext = getattr(translations, 'ugettext', None)
  148. if gettext is None:
  149. gettext = translations.gettext
  150. ngettext = getattr(translations, 'ungettext', None)
  151. if ngettext is None:
  152. ngettext = translations.ngettext
  153. self._install_callables(gettext, ngettext, newstyle)
  154. def _install_null(self, newstyle=None):
  155. self._install_callables(
  156. lambda x: x,
  157. lambda s, p, n: (n != 1 and (p,) or (s,))[0],
  158. newstyle
  159. )
  160. def _install_callables(self, gettext, ngettext, newstyle=None):
  161. if newstyle is not None:
  162. self.environment.newstyle_gettext = newstyle
  163. if self.environment.newstyle_gettext:
  164. gettext = _make_new_gettext(gettext)
  165. ngettext = _make_new_ngettext(ngettext)
  166. self.environment.globals.update(
  167. gettext=gettext,
  168. ngettext=ngettext
  169. )
  170. def _uninstall(self, translations):
  171. for key in 'gettext', 'ngettext':
  172. self.environment.globals.pop(key, None)
  173. def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):
  174. if isinstance(source, string_types):
  175. source = self.environment.parse(source)
  176. return extract_from_ast(source, gettext_functions)
  177. def parse(self, parser):
  178. """Parse a translatable tag."""
  179. lineno = next(parser.stream).lineno
  180. num_called_num = False
  181. # find all the variables referenced. Additionally a variable can be
  182. # defined in the body of the trans block too, but this is checked at
  183. # a later state.
  184. plural_expr = None
  185. plural_expr_assignment = None
  186. variables = {}
  187. while parser.stream.current.type != 'block_end':
  188. if variables:
  189. parser.stream.expect('comma')
  190. # skip colon for python compatibility
  191. if parser.stream.skip_if('colon'):
  192. break
  193. name = parser.stream.expect('name')
  194. if name.value in variables:
  195. parser.fail('translatable variable %r defined twice.' %
  196. name.value, name.lineno,
  197. exc=TemplateAssertionError)
  198. # expressions
  199. if parser.stream.current.type == 'assign':
  200. next(parser.stream)
  201. variables[name.value] = var = parser.parse_expression()
  202. else:
  203. variables[name.value] = var = nodes.Name(name.value, 'load')
  204. if plural_expr is None:
  205. if isinstance(var, nodes.Call):
  206. plural_expr = nodes.Name('_trans', 'load')
  207. variables[name.value] = plural_expr
  208. plural_expr_assignment = nodes.Assign(
  209. nodes.Name('_trans', 'store'), var)
  210. else:
  211. plural_expr = var
  212. num_called_num = name.value == 'num'
  213. parser.stream.expect('block_end')
  214. plural = plural_names = None
  215. have_plural = False
  216. referenced = set()
  217. # now parse until endtrans or pluralize
  218. singular_names, singular = self._parse_block(parser, True)
  219. if singular_names:
  220. referenced.update(singular_names)
  221. if plural_expr is None:
  222. plural_expr = nodes.Name(singular_names[0], 'load')
  223. num_called_num = singular_names[0] == 'num'
  224. # if we have a pluralize block, we parse that too
  225. if parser.stream.current.test('name:pluralize'):
  226. have_plural = True
  227. next(parser.stream)
  228. if parser.stream.current.type != 'block_end':
  229. name = parser.stream.expect('name')
  230. if name.value not in variables:
  231. parser.fail('unknown variable %r for pluralization' %
  232. name.value, name.lineno,
  233. exc=TemplateAssertionError)
  234. plural_expr = variables[name.value]
  235. num_called_num = name.value == 'num'
  236. parser.stream.expect('block_end')
  237. plural_names, plural = self._parse_block(parser, False)
  238. next(parser.stream)
  239. referenced.update(plural_names)
  240. else:
  241. next(parser.stream)
  242. # register free names as simple name expressions
  243. for var in referenced:
  244. if var not in variables:
  245. variables[var] = nodes.Name(var, 'load')
  246. if not have_plural:
  247. plural_expr = None
  248. elif plural_expr is None:
  249. parser.fail('pluralize without variables', lineno)
  250. node = self._make_node(singular, plural, variables, plural_expr,
  251. bool(referenced),
  252. num_called_num and have_plural)
  253. node.set_lineno(lineno)
  254. if plural_expr_assignment is not None:
  255. return [plural_expr_assignment, node]
  256. else:
  257. return node
  258. def _parse_block(self, parser, allow_pluralize):
  259. """Parse until the next block tag with a given name."""
  260. referenced = []
  261. buf = []
  262. while 1:
  263. if parser.stream.current.type == 'data':
  264. buf.append(parser.stream.current.value.replace('%', '%%'))
  265. next(parser.stream)
  266. elif parser.stream.current.type == 'variable_begin':
  267. next(parser.stream)
  268. name = parser.stream.expect('name').value
  269. referenced.append(name)
  270. buf.append('%%(%s)s' % name)
  271. parser.stream.expect('variable_end')
  272. elif parser.stream.current.type == 'block_begin':
  273. next(parser.stream)
  274. if parser.stream.current.test('name:endtrans'):
  275. break
  276. elif parser.stream.current.test('name:pluralize'):
  277. if allow_pluralize:
  278. break
  279. parser.fail('a translatable section can have only one '
  280. 'pluralize section')
  281. parser.fail('control structures in translatable sections are '
  282. 'not allowed')
  283. elif parser.stream.eos:
  284. parser.fail('unclosed translation block')
  285. else:
  286. assert False, 'internal parser error'
  287. return referenced, concat(buf)
  288. def _make_node(self, singular, plural, variables, plural_expr,
  289. vars_referenced, num_called_num):
  290. """Generates a useful node from the data provided."""
  291. # no variables referenced? no need to escape for old style
  292. # gettext invocations only if there are vars.
  293. if not vars_referenced and not self.environment.newstyle_gettext:
  294. singular = singular.replace('%%', '%')
  295. if plural:
  296. plural = plural.replace('%%', '%')
  297. # singular only:
  298. if plural_expr is None:
  299. gettext = nodes.Name('gettext', 'load')
  300. node = nodes.Call(gettext, [nodes.Const(singular)],
  301. [], None, None)
  302. # singular and plural
  303. else:
  304. ngettext = nodes.Name('ngettext', 'load')
  305. node = nodes.Call(ngettext, [
  306. nodes.Const(singular),
  307. nodes.Const(plural),
  308. plural_expr
  309. ], [], None, None)
  310. # in case newstyle gettext is used, the method is powerful
  311. # enough to handle the variable expansion and autoescape
  312. # handling itself
  313. if self.environment.newstyle_gettext:
  314. for key, value in iteritems(variables):
  315. # the function adds that later anyways in case num was
  316. # called num, so just skip it.
  317. if num_called_num and key == 'num':
  318. continue
  319. node.kwargs.append(nodes.Keyword(key, value))
  320. # otherwise do that here
  321. else:
  322. # mark the return value as safe if we are in an
  323. # environment with autoescaping turned on
  324. node = nodes.MarkSafeIfAutoescape(node)
  325. if variables:
  326. node = nodes.Mod(node, nodes.Dict([
  327. nodes.Pair(nodes.Const(key), value)
  328. for key, value in variables.items()
  329. ]))
  330. return nodes.Output([node])
  331. class ExprStmtExtension(Extension):
  332. """Adds a `do` tag to Jinja2 that works like the print statement just
  333. that it doesn't print the return value.
  334. """
  335. tags = set(['do'])
  336. def parse(self, parser):
  337. node = nodes.ExprStmt(lineno=next(parser.stream).lineno)
  338. node.node = parser.parse_tuple()
  339. return node
  340. class LoopControlExtension(Extension):
  341. """Adds break and continue to the template engine."""
  342. tags = set(['break', 'continue'])
  343. def parse(self, parser):
  344. token = next(parser.stream)
  345. if token.value == 'break':
  346. return nodes.Break(lineno=token.lineno)
  347. return nodes.Continue(lineno=token.lineno)
  348. class WithExtension(Extension):
  349. """Adds support for a django-like with block."""
  350. tags = set(['with'])
  351. def parse(self, parser):
  352. node = nodes.Scope(lineno=next(parser.stream).lineno)
  353. assignments = []
  354. while parser.stream.current.type != 'block_end':
  355. lineno = parser.stream.current.lineno
  356. if assignments:
  357. parser.stream.expect('comma')
  358. target = parser.parse_assign_target()
  359. parser.stream.expect('assign')
  360. expr = parser.parse_expression()
  361. assignments.append(nodes.Assign(target, expr, lineno=lineno))
  362. node.body = assignments + \
  363. list(parser.parse_statements(('name:endwith',),
  364. drop_needle=True))
  365. return node
  366. class AutoEscapeExtension(Extension):
  367. """Changes auto escape rules for a scope."""
  368. tags = set(['autoescape'])
  369. def parse(self, parser):
  370. node = nodes.ScopedEvalContextModifier(lineno=next(parser.stream).lineno)
  371. node.options = [
  372. nodes.Keyword('autoescape', parser.parse_expression())
  373. ]
  374. node.body = parser.parse_statements(('name:endautoescape',),
  375. drop_needle=True)
  376. return nodes.Scope([node])
  377. def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS,
  378. babel_style=True):
  379. """Extract localizable strings from the given template node. Per
  380. default this function returns matches in babel style that means non string
  381. parameters as well as keyword arguments are returned as `None`. This
  382. allows Babel to figure out what you really meant if you are using
  383. gettext functions that allow keyword arguments for placeholder expansion.
  384. If you don't want that behavior set the `babel_style` parameter to `False`
  385. which causes only strings to be returned and parameters are always stored
  386. in tuples. As a consequence invalid gettext calls (calls without a single
  387. string parameter or string parameters after non-string parameters) are
  388. skipped.
  389. This example explains the behavior:
  390. >>> from jinja2 import Environment
  391. >>> env = Environment()
  392. >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')
  393. >>> list(extract_from_ast(node))
  394. [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]
  395. >>> list(extract_from_ast(node, babel_style=False))
  396. [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]
  397. For every string found this function yields a ``(lineno, function,
  398. message)`` tuple, where:
  399. * ``lineno`` is the number of the line on which the string was found,
  400. * ``function`` is the name of the ``gettext`` function used (if the
  401. string was extracted from embedded Python code), and
  402. * ``message`` is the string itself (a ``unicode`` object, or a tuple
  403. of ``unicode`` objects for functions with multiple string arguments).
  404. This extraction function operates on the AST and is because of that unable
  405. to extract any comments. For comment support you have to use the babel
  406. extraction interface or extract comments yourself.
  407. """
  408. for node in node.find_all(nodes.Call):
  409. if not isinstance(node.node, nodes.Name) or \
  410. node.node.name not in gettext_functions:
  411. continue
  412. strings = []
  413. for arg in node.args:
  414. if isinstance(arg, nodes.Const) and \
  415. isinstance(arg.value, string_types):
  416. strings.append(arg.value)
  417. else:
  418. strings.append(None)
  419. for arg in node.kwargs:
  420. strings.append(None)
  421. if node.dyn_args is not None:
  422. strings.append(None)
  423. if node.dyn_kwargs is not None:
  424. strings.append(None)
  425. if not babel_style:
  426. strings = tuple(x for x in strings if x is not None)
  427. if not strings:
  428. continue
  429. else:
  430. if len(strings) == 1:
  431. strings = strings[0]
  432. else:
  433. strings = tuple(strings)
  434. yield node.lineno, node.node.name, strings
  435. class _CommentFinder(object):
  436. """Helper class to find comments in a token stream. Can only
  437. find comments for gettext calls forwards. Once the comment
  438. from line 4 is found, a comment for line 1 will not return a
  439. usable value.
  440. """
  441. def __init__(self, tokens, comment_tags):
  442. self.tokens = tokens
  443. self.comment_tags = comment_tags
  444. self.offset = 0
  445. self.last_lineno = 0
  446. def find_backwards(self, offset):
  447. try:
  448. for _, token_type, token_value in \
  449. reversed(self.tokens[self.offset:offset]):
  450. if token_type in ('comment', 'linecomment'):
  451. try:
  452. prefix, comment = token_value.split(None, 1)
  453. except ValueError:
  454. continue
  455. if prefix in self.comment_tags:
  456. return [comment.rstrip()]
  457. return []
  458. finally:
  459. self.offset = offset
  460. def find_comments(self, lineno):
  461. if not self.comment_tags or self.last_lineno > lineno:
  462. return []
  463. for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset:]):
  464. if token_lineno > lineno:
  465. return self.find_backwards(self.offset + idx)
  466. return self.find_backwards(len(self.tokens))
  467. def babel_extract(fileobj, keywords, comment_tags, options):
  468. """Babel extraction method for Jinja templates.
  469. .. versionchanged:: 2.3
  470. Basic support for translation comments was added. If `comment_tags`
  471. is now set to a list of keywords for extraction, the extractor will
  472. try to find the best preceeding comment that begins with one of the
  473. keywords. For best results, make sure to not have more than one
  474. gettext call in one line of code and the matching comment in the
  475. same line or the line before.
  476. .. versionchanged:: 2.5.1
  477. The `newstyle_gettext` flag can be set to `True` to enable newstyle
  478. gettext calls.
  479. .. versionchanged:: 2.7
  480. A `silent` option can now be provided. If set to `False` template
  481. syntax errors are propagated instead of being ignored.
  482. :param fileobj: the file-like object the messages should be extracted from
  483. :param keywords: a list of keywords (i.e. function names) that should be
  484. recognized as translation functions
  485. :param comment_tags: a list of translator tags to search for and include
  486. in the results.
  487. :param options: a dictionary of additional options (optional)
  488. :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
  489. (comments will be empty currently)
  490. """
  491. extensions = set()
  492. for extension in options.get('extensions', '').split(','):
  493. extension = extension.strip()
  494. if not extension:
  495. continue
  496. extensions.add(import_string(extension))
  497. if InternationalizationExtension not in extensions:
  498. extensions.add(InternationalizationExtension)
  499. def getbool(options, key, default=False):
  500. return options.get(key, str(default)).lower() in \
  501. ('1', 'on', 'yes', 'true')
  502. silent = getbool(options, 'silent', True)
  503. environment = Environment(
  504. options.get('block_start_string', BLOCK_START_STRING),
  505. options.get('block_end_string', BLOCK_END_STRING),
  506. options.get('variable_start_string', VARIABLE_START_STRING),
  507. options.get('variable_end_string', VARIABLE_END_STRING),
  508. options.get('comment_start_string', COMMENT_START_STRING),
  509. options.get('comment_end_string', COMMENT_END_STRING),
  510. options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,
  511. options.get('line_comment_prefix') or LINE_COMMENT_PREFIX,
  512. getbool(options, 'trim_blocks', TRIM_BLOCKS),
  513. getbool(options, 'lstrip_blocks', LSTRIP_BLOCKS),
  514. NEWLINE_SEQUENCE,
  515. getbool(options, 'keep_trailing_newline', KEEP_TRAILING_NEWLINE),
  516. frozenset(extensions),
  517. cache_size=0,
  518. auto_reload=False
  519. )
  520. if getbool(options, 'newstyle_gettext'):
  521. environment.newstyle_gettext = True
  522. source = fileobj.read().decode(options.get('encoding', 'utf-8'))
  523. try:
  524. node = environment.parse(source)
  525. tokens = list(environment.lex(environment.preprocess(source)))
  526. except TemplateSyntaxError as e:
  527. if not silent:
  528. raise
  529. # skip templates with syntax errors
  530. return
  531. finder = _CommentFinder(tokens, comment_tags)
  532. for lineno, func, message in extract_from_ast(node, keywords):
  533. yield lineno, func, message, finder.find_comments(lineno)
  534. #: nicer import names
  535. i18n = InternationalizationExtension
  536. do = ExprStmtExtension
  537. loopcontrols = LoopControlExtension
  538. with_ = WithExtension
  539. autoescape = AutoEscapeExtension