Skip to content
Myr

Biggest change to Jinja since the 1.x migration: added evaluation contexts

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

which make it possible to keep the ahead of time optimizations and provide dynamic activation and deactivation of autoescaping and other context specific features. --HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent 12a316b · Browse files · 9 files+304 added−104 removed
This commit

State

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

Diff stats

9 files+304 added−104 removed

  • other:+304 added−104 removed

9 files+304 added−104 removed

modified:jinja2/testsuite/ext.py+52 added
254 unmodified lines
255 (6, 'ngettext', (u'%(users)s user', u'%(users)s users', None), ['third'])256 ]257258259class AutoEscapeTestCase(JinjaTestCase):260261 def test_scoped_setting(self):262 env = Environment(extensions=['jinja2.ext.autoescape'],263 autoescape=True)264 tmpl = env.from_string('''265 {{ "<HelloWorld>" }}266 {% autoescape false %}267 {{ "<HelloWorld>" }}268 {% endautoescape %}269 {{ "<HelloWorld>" }}270 ''')271 assert tmpl.render().split() == \272 [u'&lt;HelloWorld&gt;', u'<HelloWorld>', u'&lt;HelloWorld&gt;']273274 env = Environment(extensions=['jinja2.ext.autoescape'],275 autoescape=False)276 tmpl = env.from_string('''277 {{ "<HelloWorld>" }}278 {% autoescape true %}279 {{ "<HelloWorld>" }}280 {% endautoescape %}281 {{ "<HelloWorld>" }}282 ''')283 assert tmpl.render().split() == \284 [u'<HelloWorld>', u'&lt;HelloWorld&gt;', u'<HelloWorld>']285286 def test_nonvolatile(self):287 env = Environment(extensions=['jinja2.ext.autoescape'],288 autoescape=True)289 tmpl = env.from_string('{{ {"foo": "<test>"}|xmlattr|escape }}')290 assert tmpl.render() == ' foo="&lt;test&gt;"'291 tmpl = env.from_string('{% autoescape false %}{{ {"foo": "<test>"}'292 '|xmlattr|escape }}{% endautoescape %}')293 assert tmpl.render() == ' foo=&#34;&amp;lt;test&amp;gt;&#34;'294295 def test_volatile(self):296 env = Environment(extensions=['jinja2.ext.autoescape'],297 autoescape=True)298 tmpl = env.from_string('{% autoescape foo %}{{ {"foo": "<test>"}'299 '|xmlattr|escape }}{% endautoescape %}')300 assert tmpl.render(foo=False) == ' foo=&#34;&amp;lt;test&amp;gt;&#34;'301 assert tmpl.render(foo=True) == ' foo="&lt;test&gt;"'302303 def test_scoping(self):304 env = Environment(extensions=['jinja2.ext.autoescape'])305 tmpl = env.from_string('{% autoescape true %}{% set x = "<x>" %}{{ x }}'306 '{% endautoescape %}{{ x }}{{ "<y>" }}')307 assert tmpl.render(x=1) == '&lt;x&gt;1<y>'308309310def suite():311 suite = unittest.TestSuite()312 suite.addTest(unittest.makeSuite(ExtensionsTestCase))313 suite.addTest(unittest.makeSuite(InternationalizationTestCase))314 suite.addTest(unittest.makeSuite(AutoEscapeTestCase))315 return suite
modified:jinja2/__init__.py+6 added-3 removed
52 unmodified lines
53 TemplateNotFound, TemplatesNotFound, TemplateSyntaxError, \54 TemplateAssertionError5556# decorators and public utilities57from jinja2.filters import environmentfilter, contextfilter57from jinja2.filters import environmentfilter, contextfilter, \58 evalcontextfilter59from jinja2.utils import Markup, escape, clear_caches, \59 environmentfunction, contextfunction, is_undefined60 environmentfunction, evalcontextfunction, contextfunction, \61 is_undefined6263__all__ = [64 'Environment', 'Template', 'BaseLoader', 'FileSystemLoader',65 'PackageLoader', 'DictLoader', 'FunctionLoader', 'PrefixLoader',
1 unmodified line
67 'MemcachedBytecodeCache', 'Undefined', 'DebugUndefined',68 'StrictUndefined', 'TemplateError', 'UndefinedError', 'TemplateNotFound',69 'TemplatesNotFound', 'TemplateSyntaxError', 'TemplateAssertionError',70 'ModuleLoader', 'environmentfilter', 'contextfilter', 'Markup', 'escape',69 'environmentfunction', 'contextfunction', 'clear_caches', 'is_undefined'71 'environmentfunction', 'contextfunction', 'clear_caches', 'is_undefined',72 'evalcontextfilter', 'evalcontextfunction'73]
modified:jinja2/compiler.py+67 added-16 removed
10 unmodified lines
11from cStringIO import StringIO12from itertools import chain13from copy import deepcopy14from jinja2 import nodes15from jinja2.nodes import EvalContext16from jinja2.visitor import NodeVisitor, NodeTransformer17from jinja2.exceptions import TemplateAssertionError18from jinja2.utils import Markup, concat, escape, is_python_keyword, next19
121 unmodified lines
141142class Frame(object):143 """Holds compile time information for us."""144144 def __init__(self, parent=None):145 def __init__(self, eval_ctx, parent=None):146 self.eval_ctx = eval_ctx147 self.identifiers = Identifiers()148149 # a toplevel frame is the root + soft frames such as if conditions.150 self.toplevel = False
61 unmodified lines
212 set(x for x in extra if i.is_declared(x))213214 def inner(self):215 """Return an inner frame."""214 return Frame(self)216 return Frame(self.eval_ctx, self)217218 def soft(self):219 """Return a soft frame. A soft frame may not be modified as220 standalone thing as it shares the resources with the frame it
202 unmodified lines
423424 # -- Various compilation helpers425426 def fail(self, msg, lineno):425 """Fail with a `TemplateAssertionError`."""427 """Fail with a :exc:`TemplateAssertionError`."""428 raise TemplateAssertionError(msg, lineno, self.name, self.filename)429430 def temporary_identifier(self):431 """Get a new unique identifier."""
6 unmodified lines
438 self.writeline('%s = []' % frame.buffer)439440 def return_buffer_contents(self, frame):441 """Return the buffer contents of the frame."""442 self.writeline('return ')443 if frame.eval_ctx.volatile:444 self.write('(Markup(concat(%s)) if context.eval_ctx'445 '.autoescape else concat(%s))' %446 (frame.buffer, frame.buffer))440 if self.environment.autoescape:441 self.writeline('return Markup(concat(%s))' % frame.buffer)447 elif frame.eval_ctx.autoescape:448 self.write('Markup(concat(%s))' % frame.buffer)449 else:443 self.writeline('return concat(%s)' % frame.buffer)450 self.write('concat(%s)' % frame.buffer)451452 def indent(self):453 """Indent by one."""454 self._indentation += 1
301 unmodified lines
756 # -- Statement Visitors757758 def visit_Template(self, node, frame=None):759 assert frame is None, 'no root frame allowed'760 eval_ctx = EvalContext(self.environment)761762 from jinja2.runtime import __all__ as exported763 self.writeline('from __future__ import division')764 self.writeline('from jinja2.runtime import ' + ', '.join(exported))765 if not unoptimize_before_dead_code:
31 unmodified lines
797 # generate the root render function.798 self.writeline('def root(context%s):' % envenv, extra=1)799800 # process the root792 frame = Frame()801 frame = Frame(eval_ctx)802 frame.inspect(node.body)803 frame.toplevel = frame.rootlevel = True804 frame.require_output_check = have_extends and not self.has_known_extends805 self.indent()
20 unmodified lines
826 self.outdent(2 + (not self.has_known_extends))827828 # at this point we now have the blocks collected and can visit them too.829 for name, block in self.blocks.iteritems():821 block_frame = Frame()830 block_frame = Frame(eval_ctx)831 block_frame.inspect(block.body)832 block_frame.block = name833 self.writeline('def block_%s(context%s):' % (name, envenv),834 block, 1)
397 unmodified lines
1232 # string at compile time.1233 body = []1234 for child in node.nodes:1235 try:1227 const = child.as_const()1236 const = child.as_const(frame.eval_ctx)1237 except nodes.Impossible:1238 body.append(child)1239 continue1240 # the frame can't be volatile here, becaus otherwise the1241 # as_const() function would raise an Impossible exception1242 # at that point.1243 try:1232 if self.environment.autoescape:1244 if frame.eval_ctx.autoescape:1245 if hasattr(const, '__html__'):1246 const = const.__html__()1247 else:1248 const = escape(const)
29 unmodified lines
1278 self.writeline('yield ', item)1279 else:1280 self.newline(item)1281 close = 11270 if self.environment.autoescape:1282 if frame.eval_ctx.volatile:1283 self.write('(context.eval_ctx.autoescape and'1284 ' escape or to_string)(')1285 elif frame.eval_ctx.autoescape:1286 self.write('escape(')1287 else:1288 self.write('to_string(')1289 if self.environment.finalize is not None:
24 unmodified lines
1314 self.indent()1315 for argument in arguments:1316 self.newline(argument)1317 close = 01303 if self.environment.autoescape:1318 if frame.eval_ctx.volatile:1319 self.write('(context.eval_ctx.autoescape and'1320 ' escape or to_string)(')1321 elif frame.eval_ctx.autoescape:1322 self.write('escape(')1323 close += 11324 if self.environment.finalize is not None:1325 self.write('environment.finalize(')
58 unmodified lines
1384 else:1385 self.write(repr(val))13861387 def visit_TemplateData(self, node, frame):1370 self.write(repr(node.as_const()))1388 self.write(repr(node.as_const(frame.eval_ctx)))13891390 def visit_Tuple(self, node, frame):1391 self.write('(')1392 idx = -1
51 unmodified lines
1444 visit_Not = uaop('not ')1445 del binop, uaop14461447 def visit_Concat(self, node, frame):1430 self.write('%s((' % (self.environment.autoescape and1431 'markup_join' or 'unicode_join'))1448 if frame.eval_ctx.volatile:1449 func_name = '(context.eval_ctx.volatile and' \1450 ' markup_join or unicode_join)'1451 elif frame.eval_ctx.autoescape:1452 func_name = 'markup_join'1453 else:1454 func_name = 'unicode_join'1455 self.write('%s((' % func_name)1456 for arg in node.nodes:1457 self.visit(arg, frame)1458 self.write(', ')1459 self.write('))')
42 unmodified lines
1502 if func is None:1503 self.fail('no filter named %r' % node.name, node.lineno)1504 if getattr(func, 'contextfilter', False):1505 self.write('context, ')1506 elif getattr(func, 'evalcontextfilter', False):1507 self.write('context.eval_ctx, ')1508 elif getattr(func, 'environmentfilter', False):1509 self.write('environment, ')15101511 # if the filter node is None we are inside a filter block1512 # and want to write to the current buffer1513 if node.node is not None:1514 self.visit(node.node, frame)1489 elif self.environment.autoescape:1515 elif frame.eval_ctx.volatile:1516 self.write('(context.eval_ctx.autoescape and'1517 ' Markup(concat(%s)) or concat(%s))' %1518 (frame.buffer, frame.buffer))1519 elif frame.eval_ctx.autoescape:1520 self.write('Markup(concat(%s))' % frame.buffer)1521 else:1522 self.write('concat(%s)' % frame.buffer)1523 self.signature(node, frame)
80 unmodified lines
1604 aliases = self.push_scope(scope_frame)1605 self.pull_locals(scope_frame)1606 self.blockvisit(node.body, scope_frame)1607 self.pop_scope(aliases, scope_frame)16081609 def visit_EvalContextModifier(self, node, frame):1610 for keyword in node.options:1611 self.writeline('context.eval_ctx.%s = ' % keyword.key)1612 self.visit(keyword.value, frame)1613 try:1614 val = keyword.value.as_const(frame.eval_ctx)1615 except nodes.Impossible:1616 frame.volatile = True1617 else:1618 setattr(frame.eval_ctx, keyword.key, val)16191620 def visit_ScopedEvalContextModifier(self, node, frame):1621 old_ctx_name = self.temporary_identifier()1622 safed_ctx = frame.eval_ctx.save()1623 self.writeline('%s = context.eval_ctx.save()' % old_ctx_name)1624 self.visit_EvalContextModifier(node, frame)1625 for child in node.body:1626 self.visit(child, frame)1627 frame.eval_ctx.revert(safed_ctx)1628 self.writeline('context.eval_ctx.revert(%s)' % old_ctx_name)
modified:jinja2/environment.py+3 added-2 removed
156 unmodified lines
157 expression before it is output. For example one can convert158 `None` implicitly into an empty string here.159160 `autoescape`161 If set to true the XML/HTML autoescaping feature is enabled.162 For more details about auto escaping see161 If set to true the XML/HTML autoescaping feature is enabled by162 default. For more details about auto escaping see163 :class:`~jinja2.utils.Markup`.164165 `loader`166 The template loader for this environment.
325 unmodified lines
492 if not parser.stream.eos:493 raise TemplateSyntaxError('chunk after expression',494 parser.stream.current.lineno,495 None, None)496 expr.set_environment(self)497 except TemplateSyntaxError:498 exc_info = sys.exc_info()499 if exc_info is not None:500 self.handle_exception(exc_info, source_hint=source)
582 unmodified lines
modified:jinja2/ext.py+15 added
355 unmodified lines
356 drop_needle=True))357 return node358359360class AutoEscapeExtension(Extension):361 """Changes auto escape rules for a scope."""362 tags = set(['autoescape'])363364 def parse(self, parser):365 node = nodes.ScopedEvalContextModifier(lineno=next(parser.stream).lineno)366 node.options = [367 nodes.Keyword('autoescape', parser.parse_expression())368 ]369 node.body = parser.parse_statements(('name:endautoescape',),370 drop_needle=True)371 return nodes.Scope([node])372373374def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS,375 babel_style=True):376 """Extract localizable strings from the given template node. Per377 default this function returns matches in babel style that means non string
164 unmodified lines
542i18n = InternationalizationExtension543do = ExprStmtExtension544loopcontrols = LoopControlExtension545with_ = WithExtension546autoescape = AutoEscapeExtension
modified:jinja2/filters.py+22 added-16 removed
23 unmodified lines
24def contextfilter(f):25 """Decorator for marking context dependent filters. The current26 :class:`Context` will be passed as first argument.27 """28 if getattr(f, 'environmentfilter', False):29 raise TypeError('filter already marked as environment filter')28 f.contextfilter = True29 return f303132def evalcontextfilter(f):33 """Decorator for marking eval-context dependent filters. An eval34 context object is passed as first argument.3536 .. versionadded:: 2.437 """38 f.evalcontextfilter = True39 return f404142def environmentfilter(f):43 """Decorator for marking evironment dependent filters. The current44 :class:`Environment` is passed to the filter as first argument.45 """38 if getattr(f, 'contextfilter', False):39 raise TypeError('filter already marked as context filter')46 f.environmentfilter = True47 return f4849
3 unmodified lines
53 value = value.__html__()54 return escape(unicode(value))555651@environmentfilter52def do_replace(environment, s, old, new, count=None):57@evalcontextfilter58def do_replace(eval_ctx, s, old, new, count=None):59 """Return a copy of the value with all occurrences of a substring60 replaced with a new one. The first argument is the substring61 that should be replaced, the second is the replacement string.62 If the optional third argument ``count`` is given, only the first
8 unmodified lines
71 -> d'oh, d'oh, aaargh72 """73 if count is None:74 count = -169 if not environment.autoescape:75 if not eval_ctx.autoescape:76 return unicode(s).replace(unicode(old), unicode(new), count)77 if hasattr(old, '__html__') or hasattr(new, '__html__') and \78 not hasattr(s, '__html__'):79 s = escape(s)
11 unmodified lines
91 """Convert a value to lowercase."""92 return soft_unicode(s).lower()939489@environmentfilter90def do_xmlattr(_environment, d, autospace=True):95@evalcontextfilter96def do_xmlattr(_eval_ctx, d, autospace=True):97 """Create an SGML/XML attribute string based on the items in a dict.98 All values that are neither `none` nor `undefined` are automatically99 escaped:100
21 unmodified lines
122 if value is not None and not isinstance(value, Undefined)123 )124 if autospace and rv:125 rv = u' ' + rv120 if _environment.autoescape:126 if _eval_ctx.autoescape:127 rv = Markup(rv)128 return rv129130
86 unmodified lines
217 return default_value218 return value219220215@environmentfilter216def do_join(environment, value, d=u''):221@evalcontextfilter222def do_join(eval_ctx, value, d=u''):223 """Return a string which is the concatenation of the strings in the224 sequence. The separator between elements is an empty string per225 default, you can define it with the optional parameter:226
5 unmodified lines
232 {{ [1, 2, 3]|join }}233 -> 123234 """235 # no automatic escaping? joining is a lot eaiser then230 if not environment.autoescape:236 if not eval_ctx.autoescape:237 return unicode(d).join(imap(unicode, value))238239 # if the delimiter doesn't have an html representation we check240 # if any of the items has. If yes we do a coercion to Markup
73 unmodified lines
314 """315 return pformat(value, verbose=verbose)316317312@environmentfilter313def do_urlize(environment, value, trim_url_limit=None, nofollow=False):318@evalcontextfilter319def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False):320 """Converts URLs in plain text into clickable links.321322 If you pass the filter an additional integer it will shorten the urls323 to that number. Also a third argument exists that makes the urls
4 unmodified lines
328 {{ mytext|urlize(40, true) }}329 links are shortened to 40 chars and defined with rel="nofollow"330 """331 rv = urlize(value, trim_url_limit, nofollow)326 if environment.autoescape:332 if eval_ctx.autoescape:333 rv = Markup(rv)334 return rv335336
393 unmodified lines
modified:jinja2/nodes.py+120 added-65 removed
65 unmodified lines
66 d.setdefault('abstract', False)67 return type.__new__(cls, name, bases, d)686970class EvalContext(object):71 """Holds evaluation time information"""7273 def __init__(self, environment):74 self.autoescape = environment.autoescape75 self.volatile = False7677 def save(self):78 return self.__dict__.copy()7980 def revert(self, old):81 self.__dict__.clear()82 self.__dict__.update(old)838485def get_eval_context(node, ctx):86 if ctx is None:87 if node.environment is None:88 raise RuntimeError('if no eval context is passed, the '89 'node must have an attached '90 'environment.')91 return EvalContext(node.environment)92 return ctx939495class Node(object):96 """Baseclass for all Jinja2 nodes. There are a number of nodes available97 of different types. There are three major types:98
237 unmodified lines
336class Expr(Node):337 """Baseclass for all expressions."""338 abstract = True339315 def as_const(self):340 def as_const(self, eval_ctx=None):341 """Return the value of the expression as constant or raise317 :exc:`Impossible` if this was not possible:342 :exc:`Impossible` if this was not possible.343319 >>> Add(Const(23), Const(42)).as_const()320 65321 >>> Add(Const(23), Name('var', 'load')).as_const()322 Traceback (most recent call last):323 ...324 Impossible344 An :class:`EvalContext` can be provided, if none is given345 a default context is created which requires the nodes to have346 an attached environment.347326 This requires the `environment` attribute of all nodes to be327 set to the environment that created the nodes.348 .. versionchanged:: 2.4349 the `eval_ctx` parameter was added.350 """351 raise Impossible()352353 def can_assign(self):
6 unmodified lines
360 fields = ('left', 'right')361 operator = None362 abstract = True363342 def as_const(self):364 def as_const(self, eval_ctx=None):365 eval_ctx = get_eval_context(self, eval_ctx)366 f = _binop_to_func[self.operator]367 try:345 return f(self.left.as_const(), self.right.as_const())368 return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))369 except:370 raise Impossible()371372
2 unmodified lines
375 fields = ('node',)376 operator = None377 abstract = True378356 def as_const(self):379 def as_const(self, eval_ctx=None):380 eval_ctx = get_eval_context(self, eval_ctx)381 f = _uaop_to_func[self.operator]382 try:359 return f(self.node.as_const())383 return f(self.node.as_const(eval_ctx))384 except:385 raise Impossible()386387
24 unmodified lines
412 representation (objects where ``eval(repr(x)) == x`` is true).413 """414 fields = ('value',)415392 def as_const(self):416 def as_const(self, eval_ctx=None):417 return self.value418419 @classmethod420 def from_untrusted(cls, value, lineno=None, environment=None):
10 unmodified lines
431class TemplateData(Literal):432 """A constant template string."""433 fields = ('data',)434411 def as_const(self):412 if self.environment.autoescape:435 def as_const(self, eval_ctx=None):436 if get_eval_context(self, eval_ctx).autoescape:437 return Markup(self.data)438 return self.data439440
3 unmodified lines
444 is used for loading the names or storing.445 """446 fields = ('items', 'ctx')447424 def as_const(self):425 return tuple(x.as_const() for x in self.items)448 def as_const(self, eval_ctx=None):449 eval_ctx = get_eval_context(self, eval_ctx)450 return tuple(x.as_const(eval_ctx) for x in self.items)451452 def can_assign(self):453 for item in self.items:454 if not item.can_assign():
4 unmodified lines
459class List(Literal):460 """Any list literal such as ``[1, 2, 3]``"""461 fields = ('items',)462438 def as_const(self):439 return [x.as_const() for x in self.items]463 def as_const(self, eval_ctx=None):464 eval_ctx = get_eval_context(self, eval_ctx)465 return [x.as_const(eval_ctx) for x in self.items]466467468class Dict(Literal):469 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of470 :class:`Pair` nodes.471 """472 fields = ('items',)473448 def as_const(self):449 return dict(x.as_const() for x in self.items)474 def as_const(self, eval_ctx=None):475 eval_ctx = get_eval_context(self, eval_ctx)476 return dict(x.as_const(eval_ctx) for x in self.items)477478479class Pair(Helper):480 """A key, value pair for dicts."""481 fields = ('key', 'value')482456 def as_const(self):457 return self.key.as_const(), self.value.as_const()483 def as_const(self, eval_ctx=None):484 eval_ctx = get_eval_context(self, eval_ctx)485 return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)486487488class Keyword(Helper):489 """A key, value pair for keyword arguments where key is a string."""490 fields = ('key', 'value')491464 def as_const(self):465 return self.key, self.value.as_const()492 def as_const(self, eval_ctx=None):493 eval_ctx = get_eval_context(self, eval_ctx)494 return self.key, self.value.as_const(eval_ctx)495496497class CondExpr(Expr):498 """A conditional expression (inline if expression). (``{{499 foo if bar else baz }}``)500 """501 fields = ('test', 'expr1', 'expr2')502474 def as_const(self):475 if self.test.as_const():476 return self.expr1.as_const()503 def as_const(self, eval_ctx=None):504 eval_ctx = get_eval_context(self, eval_ctx)505 if self.test.as_const(eval_ctx):506 return self.expr1.as_const(eval_ctx)507508 # if we evaluate to an undefined object, we better do that at runtime509 if self.expr2 is None:510 raise Impossible()511482 return self.expr2.as_const()512 return self.expr2.as_const(eval_ctx)513514515class Filter(Expr):516 """This node applies a filter on an expression. `name` is the name of
3 unmodified lines
520 filtered. Buffers are created by macros and filter blocks.521 """522 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')523494 def as_const(self, obj=None):495 if self.node is obj is None:524 def as_const(self, eval_ctx=None):525 eval_ctx = get_eval_context(self, eval_ctx)526 if eval_ctx.volatile or self.node is None:527 raise Impossible()528 # we have to be careful here because we call filter_ below.529 # if this variable would be called filter, 2to3 would wrap the530 # call in a list beause it is assuming we are talking about the
1 unmodified line
532 # python 3. because of that, do not rename filter_ to filter!533 filter_ = self.environment.filters.get(self.name)534 if filter_ is None or getattr(filter_, 'contextfilter', False):535 raise Impossible()505 if obj is None:506 obj = self.node.as_const()507 args = [x.as_const() for x in self.args]508 if getattr(filter_, 'environmentfilter', False):536 obj = self.node.as_const(eval_ctx)537 args = [x.as_const(eval_ctx) for x in self.args]538 if getattr(filter_, 'evalcontextfilter', False):539 args.insert(0, eval_ctx)540 elif getattr(filter_, 'environmentfilter', False):541 args.insert(0, self.environment)510 kwargs = dict(x.as_const() for x in self.kwargs)542 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)543 if self.dyn_args is not None:544 try:513 args.extend(self.dyn_args.as_const())545 args.extend(self.dyn_args.as_const(eval_ctx))546 except:547 raise Impossible()548 if self.dyn_kwargs is not None:549 try:518 kwargs.update(self.dyn_kwargs.as_const())550 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))551 except:552 raise Impossible()553 try:554 return filter_(obj, *args, **kwargs)
16 unmodified lines
571 arguments.572 """573 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')574543 def as_const(self):544 obj = self.node.as_const()575 def as_const(self, eval_ctx=None):576 eval_ctx = get_eval_context(self, eval_ctx)577 if eval_ctx.volatile:578 raise Impossible()579 obj = self.node.as_const(eval_ctx)580581 # don't evaluate context functions547 args = [x.as_const() for x in self.args]582 args = [x.as_const(eval_ctx) for x in self.args]583 if getattr(obj, 'contextfunction', False):584 raise Impossible()585 elif getattr(obj, 'evalcontextfunction', False):586 args.insert(0, eval_ctx)587 elif getattr(obj, 'environmentfunction', False):588 args.insert(0, self.environment)589553 kwargs = dict(x.as_const() for x in self.kwargs)590 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)591 if self.dyn_args is not None:592 try:556 args.extend(self.dyn_args.as_const())593 args.extend(self.dyn_args.as_const(eval_ctx))594 except:595 raise Impossible()596 if self.dyn_kwargs is not None:597 try:561 kwargs.update(self.dyn_kwargs.as_const())598 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))599 except:600 raise Impossible()601 try:602 return obj(*args, **kwargs)
4 unmodified lines
607class Getitem(Expr):608 """Get an attribute or item from an expression and prefer the item."""609 fields = ('node', 'arg', 'ctx')610574 def as_const(self):611 def as_const(self, eval_ctx=None):612 eval_ctx = get_eval_context(self, eval_ctx)613 if self.ctx != 'load':614 raise Impossible()615 try:578 return self.environment.getitem(self.node.as_const(),579 self.arg.as_const())616 return self.environment.getitem(self.node.as_const(eval_ctx),617 self.arg.as_const(eval_ctx))618 except:619 raise Impossible()620621 def can_assign(self):
5 unmodified lines
627 bytestring and prefer the attribute.628 """629 fields = ('node', 'attr', 'ctx')630593 def as_const(self):631 def as_const(self, eval_ctx=None):632 if self.ctx != 'load':633 raise Impossible()634 try:635 eval_ctx = get_eval_context(self, eval_ctx)597 return self.environment.getattr(self.node.as_const(), arg)636 return self.environment.getattr(self.node.as_const(eval_ctx), arg)637 except:638 raise Impossible()639640 def can_assign(self):
5 unmodified lines
646 :class:`Subscript`.647 """648 fields = ('start', 'stop', 'step')649611 def as_const(self):650 def as_const(self, eval_ctx=None):651 eval_ctx = get_eval_context(self, eval_ctx)652 def const(obj):653 if obj is None:614 return obj615 return obj.as_const()654 return None655 return obj.as_const(eval_ctx)656 return slice(const(self.start), const(self.stop), const(self.step))657658659class Concat(Expr):
1 unmodified line
661 unicode.662 """663 fields = ('nodes',)664625 def as_const(self):626 return ''.join(unicode(x.as_const()) for x in self.nodes)665 def as_const(self, eval_ctx=None):666 eval_ctx = get_eval_context(self, eval_ctx)667 return ''.join(unicode(x.as_const(eval_ctx)) for x in self.nodes)668669670class Compare(Expr):671 """Compares an expression with some other expressions. `ops` must be a672 list of :class:`Operand`\s.673 """674 fields = ('expr', 'ops')675635 def as_const(self):636 result = value = self.expr.as_const()676 def as_const(self, eval_ctx=None):677 eval_ctx = get_eval_context(self, eval_ctx)678 result = value = self.expr.as_const(eval_ctx)679 try:680 for op in self.ops:639 new_value = op.expr.as_const()681 new_value = op.expr.as_const(eval_ctx)682 result = _cmpop_to_func[op.op](value, new_value)683 value = new_value684 except:685 raise Impossible()
50 unmodified lines
736class And(BinExpr):737 """Short circuited AND."""738 operator = 'and'739698 def as_const(self):699 return self.left.as_const() and self.right.as_const()740 def as_const(self, eval_ctx=None):741 eval_ctx = get_eval_context(self, eval_ctx)742 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)743744745class Or(BinExpr):746 """Short circuited OR."""747 operator = 'or'748706 def as_const(self):707 return self.left.as_const() or self.right.as_const()749 def as_const(self, eval_ctx=None):750 eval_ctx = get_eval_context(self, eval_ctx)751 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)752753754class Not(UnaryExpr):755 """Negate the expression."""
56 unmodified lines
812class MarkSafe(Expr):813 """Mark the wrapped expression as safe (wrap it as `Markup`)."""814 fields = ('expr',)815772 def as_const(self):773 return Markup(self.expr.as_const())816 def as_const(self, eval_ctx=None):817 eval_ctx = get_eval_context(self, eval_ctx)818 return Markup(self.expr.as_const(eval_ctx))819820821class ContextReference(Expr):822 """Returns the current template context."""
11 unmodified lines
834 """An artificial scope."""835 fields = ('body',)836837838class EvalContextModifier(Stmt):839 """Modifies the eval context"""840 fields = ('options',)841842843class ScopedEvalContextModifier(EvalContextModifier):844 """Modifies the eval context and reverts it later."""845 fields = ('body',)846847848# make sure nobody creates custom nodes849def _failing_new(*args, **kwargs):850 raise TypeError('can\'t create custom node types')851NodeType.__new__ = staticmethod(_failing_new); del _failing_new
modified:jinja2/runtime.py+7 added-2 removed
8 unmodified lines
9 :license: BSD.10"""11import sys12from itertools import chain, imap13from jinja2.nodes import EvalContext14from jinja2.utils import Markup, partial, soft_unicode, escape, missing, \15 concat, MethodType, FunctionType, internalcode, next16from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \17 TemplateNotFound
88 unmodified lines
106 `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`107 method that doesn't fail with a `KeyError` but returns an108 :class:`Undefined` object for missing variables.109 """109 __slots__ = ('parent', 'vars', 'environment', 'exported_vars', 'name',110 'blocks', '__weakref__')110 __slots__ = ('parent', 'vars', 'environment', 'eval_ctx', 'exported_vars',111 'name', 'blocks', '__weakref__')112113 def __init__(self, environment, parent, name, blocks):114 self.parent = parent115 self.vars = {}116 self.environment = environment117 self.eval_ctx = EvalContext(self.environment)118 self.exported_vars = set()119 self.name = name120121 # create the initial mapping of blocks. Whenever template inheritance
53 unmodified lines
175 __traceback_hide__ = True176 if isinstance(__obj, _context_function_types):177 if getattr(__obj, 'contextfunction', 0):178 args = (__self,) + args179 elif getattr(__obj, 'evalcontextfunction', 0):180 args = (__self.eval_ctx,) + args181 elif getattr(__obj, 'environmentfunction', 0):182 args = (__self.environment,) + args183 return __obj(*args, **kwargs)184185 def derived(self, locals=None):186 """Internal helper function to create a derived context."""187 context = new_context(self.environment, self.name, {},188 self.parent, True, None, locals)189 context.eval_ctx = self.eval_ctx190 context.blocks.update((k, list(v)) for k, v in self.blocks.iteritems())191 return context192193 def _all(meth):
343 unmodified lines
modified:jinja2/utils.py+12 added
125 unmodified lines
126 f.contextfunction = True127 return f128129130def evalcontextfunction(f):131 """This decoraotr can be used to mark a function or method as an eval132 context callable. This is similar to the :func:`contextfunction`133 but instead of passing the context, an evaluation context object is134 passed.135136 .. versionadded:: 2.4137 """138 f.evalcontextfunction = True139 return f140141142def environmentfunction(f):143 """This decorator can be used to mark a function or method as environment144 callable. This decorator works exactly like the :func:`contextfunction`145 decorator just that the first argument is the active :class:`Environment`
656 unmodified lines