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
Provenance
- Commit
ba6e25a- Tree
7ccc032- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
9efe081
8 files changed+102 added−18 removed
modified:docs/api.rst+1 added-1 removed
113 unmodified lines114 useful if you want to dig deeper into Jinja2 or :ref:`develop extensions115 <jinja-extensions>`.116 117 .. autoclass:: Environment([options])118- :members: from_string, get_template, join_path, extend118+ :members: from_string, get_template, join_path, extend, compile_expression119 120 .. attribute:: shared121 122 If a template was created by using the :class:`Template` constructor545 unmodified linesmodified:jinja2/environment.py+68 added-5 removed
7 unmodified lines8 :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 import sys12+from jinja2 import nodes13 from jinja2.defaults import *14 from jinja2.lexer import get_lexer, TokenStream15 from jinja2.parser import Parser16 from jinja2.optimizer import optimize17 from jinja2.compiler import generate18 from jinja2.runtime import Undefined, Context19 from jinja2.exceptions import TemplateSyntaxError19-from jinja2.utils import import_string, LRUCache, Markup, missing, concat20+from jinja2.utils import import_string, LRUCache, Markup, missing, \21+ concat, consume22 23 24 # for direct template usage we have up to ten living environments25 _spontaneous_environments = LRUCache(10)354 unmodified lines380 """381 return reduce(lambda s, e: e.preprocess(s, name, filename),382 self.extensions.itervalues(), unicode(source))383 382- 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 lines408 """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')421 422+ 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.426+427+ This is useful if applications want to use the same rules as Jinja428+ in template "configuration files" or similar situations.429+430+ Example usage:431+432+ >>> env = Environment()433+ >>> expr = env.compile_expression('foo == 42')434+ >>> expr(foo=23)435+ False436+ >>> expr(foo=42)437+ True438+439+ 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`.442+443+ >>> env.compile_expression('var')() is None444+ True445+ >>> env.compile_expression('var', undefined_to_none=False)()446+ Undefined447+448+ **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)463+464 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 the274 unmodified lines742 name = repr(self.__name__)743 return '<%s %s>' % (self.__class__.__name__, name)744 745 746+class 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+ """751+752+ def __init__(self, template, undefined_to_none):753+ self._template = template754+ self._undefined_to_none = undefined_to_none755+756+ 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 rv763+764+765 class 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 unbuffered80 unmodified linesmodified:jinja2/lexer.py+9 added-4 removed
373 unmodified lines374 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)377 378- 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)383 384 def wrap(self, stream, name=None, filename=None):385 """This is called with the stream as returned by `tokenize` and wraps39 unmodified lines425 elif token == 'operator':426 token = operators[value]427 yield Token(lineno, token, value)428 429- 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)444 445 balancing_stack = []446 115 unmodified linesmodified:jinja2/nodes.py-5 removed
260 unmodified lines261 """262 fields = ('call', 'args', 'defaults', 'body')263 264 265-class Set(Stmt):266- """Allows defining own variables."""267- fields = ('name', 'expr')268-269-265 class FilterBlock(Stmt):266 """Node for filter sections."""267 fields = ('body', 'filter')268 516 unmodified linesmodified:jinja2/parser.py+3 added-2 removed
21 unmodified lines22 """This is the central parsing class Jinja2 uses. It's passed to23 extensions and can be used to parse expressions or statements.24 """25 26- 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 linesmodified:jinja2/utils.py+6 added
134 unmodified lines135 from jinja2.runtime import Undefined136 return isinstance(obj, Undefined)137 138 139+def consume(iterable):140+ """Consumes an iterable without doing anything with it."""141+ for event in iterable:142+ pass143+144+145 def 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 are600 unmodified linesmodified:tests/test_various.py+12 added-1 removed
6 unmodified lines7 :license: BSD, see LICENSE for more details.8 """9 import gc10 from py.test import raises11-from jinja2 import escape11+from jinja2 import escape, is_undefined12 from jinja2.utils import Cycler13 from jinja2.exceptions import TemplateSyntaxError14 15 80 unmodified lines96 c.next()97 assert c.current == 298 c.reset()99 assert c.current == 1100+101+102+def 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())108+109+ expr = env.compile_expression("42 + foo")110+ assert expr(foo=42) == 84modified:CHANGES+3 added
39 unmodified lines40 - added a cycle helper called `cycler`.41 42 - added a joining helper called `joiner`.43 44+- added a `compile_expression` method to the environment that allows compiling45+ of Jinja expressions into callable Python objects.46+47 Version 2.048 -----------49 (codename jinjavitus, released on July 17th 2008)50 32 unmodified lines