Skip to content
Myr

Added support for `Environment.compile_expression`.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent 9efe081 · Browse files · 8 files+102 added−18 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+102 added−18 removed

  • tests:+12 added−1 removed
  • other:+90 added−17 removed

8 files+102 added−18 removed

modified:docs/api.rst+1 added-1 removed
113 unmodified lines
114useful if you want to dig deeper into Jinja2 or :ref:`develop extensions115<jinja-extensions>`.116117.. autoclass:: Environment([options])118 :members: from_string, get_template, join_path, extend118 :members: from_string, get_template, join_path, extend, compile_expression119120 .. attribute:: shared121122 If a template was created by using the :class:`Template` constructor
545 unmodified lines
modified:jinja2/environment.py+68 added-5 removed
7 unmodified lines
8 :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import sys12from jinja2 import nodes13from jinja2.defaults import *14from jinja2.lexer import get_lexer, TokenStream15from jinja2.parser import Parser16from jinja2.optimizer import optimize17from jinja2.compiler import generate18from jinja2.runtime import Undefined, Context19from jinja2.exceptions import TemplateSyntaxError19from jinja2.utils import import_string, LRUCache, Markup, missing, concat20from jinja2.utils import import_string, LRUCache, Markup, missing, \21 concat, consume222324# for direct template usage we have up to ten living environments25_spontaneous_environments = LRUCache(10)
354 unmodified lines
380 """381 return reduce(lambda s, e: e.preprocess(s, name, filename),382 self.extensions.itervalues(), unicode(source))383382 def _tokenize(self, source, name, filename=None):384 def _tokenize(self, source, name, filename=None, state=None):385 """Called by the parser to do the preprocessing and filtering386 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.387 """388 source = self.preprocess(source, name, filename)387 stream = self.lexer.tokenize(source, name, filename)389 stream = self.lexer.tokenize(source, name, filename, state)390 for ext in self.extensions.itervalues():391 stream = ext.filter_stream(stream)392 if not isinstance(stream, TokenStream):393 stream = TokenStream(stream, name, filename)
14 unmodified lines
408 """409 if isinstance(source, basestring):410 source = self.parse(source, name, filename)411 if self.optimized:410 node = optimize(source, self)411 source = generate(node, self, name, filename)412 source = optimize(source, self)413 source = generate(source, self, name, filename)414 if raw:415 return source416 if filename is None:417 filename = '<template>'418 elif isinstance(filename, unicode):419 filename = filename.encode('utf-8')420 return compile(source, filename, 'exec')421422 def compile_expression(self, source, undefined_to_none=True):423 """A handy helper method that returns a callable that accepts keyword424 arguments that appear as variables in the expression. If called it425 returns the result of the expression.426427 This is useful if applications want to use the same rules as Jinja428 in template "configuration files" or similar situations.429430 Example usage:431432 >>> env = Environment()433 >>> expr = env.compile_expression('foo == 42')434 >>> expr(foo=23)435 False436 >>> expr(foo=42)437 True438439 Per default the return value is converted to `None` if the440 expression returns an undefined value. This can be changed441 by setting `undefined_to_none` to `False`.442443 >>> env.compile_expression('var')() is None444 True445 >>> env.compile_expression('var', undefined_to_none=False)()446 Undefined447448 **new in Jinja 2.1**449 """450 parser = Parser(self, source, state='variable')451 try:452 expr = parser.parse_expression()453 if not parser.stream.eos:454 raise TemplateSyntaxError('chunk after expression',455 parser.stream.current.lineno,456 None, None)457 except TemplateSyntaxError, e:458 e.source = source459 raise e460 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]461 template = self.from_string(nodes.Template(body, lineno=1))462 return TemplateExpression(template, undefined_to_none)463464 def join_path(self, template, parent):465 """Join a template with the parent. By default all the lookups are466 relative to the loader root so this method returns the `template`467 parameter unchanged, but if the paths should be relative to the
274 unmodified lines
742 name = repr(self.__name__)743 return '<%s %s>' % (self.__class__.__name__, name)744745746class TemplateExpression(object):747 """The :meth:`jinja2.Environment.compile_expression` method returns an748 instance of this object. It encapsulates the expression-like access749 to the template with an expression it wraps.750 """751752 def __init__(self, template, undefined_to_none):753 self._template = template754 self._undefined_to_none = undefined_to_none755756 def __call__(self, *args, **kwargs):757 context = self._template.new_context(dict(*args, **kwargs))758 consume(self._template.root_render_func(context))759 rv = context.vars['result']760 if self._undefined_to_none and isinstance(rv, Undefined):761 rv = None762 return rv763764765class TemplateStream(object):766 """A template stream works pretty much like an ordinary python generator767 but it can buffer multiple items to reduce the number of total iterations.768 Per default the output is unbuffered which means that for every unbuffered
80 unmodified lines
modified:jinja2/lexer.py+9 added-4 removed
373 unmodified lines
374 def _normalize_newlines(self, value):375 """Called for strings and template data to normlize it to unicode."""376 return newline_re.sub(self.newline_sequence, value)377378 def tokenize(self, source, name=None, filename=None):378 def tokenize(self, source, name=None, filename=None, state=None):379 """Calls tokeniter + tokenize and wraps it in a token stream.380 """381 stream = self.tokeniter(source, name, filename)381 stream = self.tokeniter(source, name, filename, state)382 return TokenStream(self.wrap(stream, name, filename), name, filename)383384 def wrap(self, stream, name=None, filename=None):385 """This is called with the stream as returned by `tokenize` and wraps
39 unmodified lines
425 elif token == 'operator':426 token = operators[value]427 yield Token(lineno, token, value)428429 def tokeniter(self, source, name, filename=None):429 def tokeniter(self, source, name, filename=None, state=None):430 """This method tokenizes the text and returns the tokens in a431 generator. Use this method if you just want to tokenize a template.432 """433 source = '\n'.join(unicode(source).splitlines())434 pos = 0435 lineno = 1436 stack = ['root']437 if state is not None and state != 'root':438 assert state in ('variable', 'block'), 'invalid state'439 stack.append(state + '_begin')440 else:441 state = 'root'437 statetokens = self.rules['root']442 statetokens = self.rules[stack[-1]]443 source_length = len(source)444445 balancing_stack = []446
115 unmodified lines
modified:jinja2/nodes.py-5 removed
260 unmodified lines
261 """262 fields = ('call', 'args', 'defaults', 'body')263264265class Set(Stmt):266 """Allows defining own variables."""267 fields = ('name', 'expr')268269265class FilterBlock(Stmt):266 """Node for filter sections."""267 fields = ('body', 'filter')268
516 unmodified lines
modified:jinja2/parser.py+3 added-2 removed
21 unmodified lines
22 """This is the central parsing class Jinja2 uses. It's passed to23 extensions and can be used to parse expressions or statements.24 """2526 def __init__(self, environment, source, name=None, filename=None):26 def __init__(self, environment, source, name=None, filename=None,27 state=None):28 self.environment = environment28 self.stream = environment._tokenize(source, name, filename)29 self.stream = environment._tokenize(source, name, filename, state)30 self.name = name31 self.filename = filename32 self.closed = False33 self.extensions = {}
741 unmodified lines
modified:jinja2/utils.py+6 added
134 unmodified lines
135 from jinja2.runtime import Undefined136 return isinstance(obj, Undefined)137138139def consume(iterable):140 """Consumes an iterable without doing anything with it."""141 for event in iterable:142 pass143144145def clear_caches():146 """Jinja2 keeps internal caches for environments and lexers. These are147 used so that Jinja2 doesn't have to recreate environments and lexers all148 the time. Normally you don't have to care about that but if you are
600 unmodified lines
modified:tests/test_various.py+12 added-1 removed
6 unmodified lines
7 :license: BSD, see LICENSE for more details.8"""9import gc10from py.test import raises11from jinja2 import escape11from jinja2 import escape, is_undefined12from jinja2.utils import Cycler13from jinja2.exceptions import TemplateSyntaxError1415
80 unmodified lines
96 c.next()97 assert c.current == 298 c.reset()99 assert c.current == 1100101102def test_expressions(env):103 expr = env.compile_expression("foo")104 assert expr() is None105 assert expr(foo=42) == 42106 expr2 = env.compile_expression("foo", undefined_to_none=False)107 assert is_undefined(expr2())108109 expr = env.compile_expression("42 + foo")110 assert expr(foo=42) == 84
modified:CHANGES+3 added
39 unmodified lines
40- added a cycle helper called `cycler`.4142- added a joining helper called `joiner`.4344- added a `compile_expression` method to the environment that allows compiling45 of Jinja expressions into callable Python objects.4647Version 2.048-----------49(codename jinjavitus, released on July 17th 2008)50
32 unmodified lines