Merge branch 'master' into 557-map-default
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parents 8b09b03, 04cc41e · Browse files · 31 files·+580 added−214 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
31 files+580 added−214 removed
- tests:+154 added−21 removed
- other:+426 added−193 removed
Provenance
- Commit
8178361- Tree
d3ab679- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
8b09b03- Parent 2
04cc41e
31 files changed+580 added−214 removed
modified:docs/api.rst+6 added-3 removed
1 API2 ===3 4 .. module:: jinja25+ :noindex:6 :synopsis: public Jinja2 API7 8 This document describes the API to Jinja2 and not the template language. It9 will be most useful as reference to those implementing the template interface36 unmodified lines46 template = env.get_template('mytemplate.html')47 48 To render it with some variables, just call the :meth:`render` method::49 49- print template.render(the='variables', go='here')50+ print(template.render(the='variables', go='here'))51 52 Using a template loader rather than passing strings to :class:`Template`53 or :meth:`Environment.from_string` has multiple advantages. Besides being54 a lot easier to use it also enables template inheritance.267 unmodified lines322 unable to look up a name or access an attribute one of those objects is323 created and returned. Some operations on undefined values are then allowed,324 others fail.325 325-The closest to regular Python behavior is the `StrictUndefined` which326+The closest to regular Python behavior is the :class:`StrictUndefined` which327 disallows all operations beside testing if it's an undefined object.328 329 .. autoclass:: jinja2.Undefined()330 22 unmodified lines353 When called with any arguments this method raises354 :attr:`_undefined_exception` with an error message generated355 from the undefined hints stored on the undefined object.356 357+.. autoclass:: jinja2.ChainableUndefined()358+359 .. autoclass:: jinja2.DebugUndefined()360 361 .. autoclass:: jinja2.StrictUndefined()362 473 unmodified lines836 837 def is_prime(n):838 if n == 2:839 return True837- for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):840+ for i in range(2, int(math.ceil(math.sqrt(n))) + 1):841 if n % i == 0:842 return False843 return True844 91 unmodified linesmodified:docs/faq.rst+1 added-2 removed
151 unmodified lines152 153 Python 2.3 is missing a lot of features that are used heavily in Jinja2. This154 decision was made as with the upcoming Python 2.6 and 3.0 versions it becomes155 harder to maintain the code for older Python versions. If you really need156-Python 2.3 support you either have to use `Jinja 1`_ or other templating156+Python 2.3 support you either have to use Jinja 1 or other templating157 engines that still support 2.3.158 159 Python 2.4/2.5/3.1/3.2 support was removed when we switched to supporting160 Python 2 and 3 by the same sourcecode (without using 2to3). It was required to30 unmodified lines191 templates passing information to the parent template. To avoid this192 issue rename the macro or variable in the parent template to have an193 uncommon prefix.194 195-.. _Jinja 1: http://jinja.pocoo.org/1/modified:docs/templates.rst+62 added-6 removed
393 unmodified lines394 this template "extends" another template. When the template system evaluates395 this template, it first locates the parent. The extends tag should be the396 first tag in the template. Everything before it is printed out normally and397 may cause confusion. For details about this behavior and how to take398-advantage of it, see :ref:`null-master-fallback`.398+advantage of it, see :ref:`null-master-fallback`. Also a block will always be399+filled in regardless of whether the surrounding condition is evaluated to be true 400+or false.401 402 The filename of the template depends on the template loader. For example, the403 :class:`FileSystemLoader` allows you to access other templates by giving the404 filename. You can access templates in subdirectories with a slash::21 unmodified lines426 427 Super Blocks428 ~~~~~~~~~~~~429 428-It's possible to render the contents of the parent block by calling `super`.430+It's possible to render the contents of the parent block by calling ``super()``.431 This gives back the results of the parent block::432 433 {% block sidebar %}434 <h3>Table Of Contents</h3>1 unmodified line436 {{ super() }}437 {% endblock %}438 439 440+Nesting extends441+~~~~~~~~~~~~~~~442+443+In the case of multiple levels of ``{% extends %}``,444+``super`` references may be chained (as in ``super.super()``)445+to skip levels in the inheritance tree.446+447+For example::448+449+ # parent.tmpl450+ body: {% block body %}Hi from parent.{% endblock %}451+452+ # child.tmpl453+ {% extends "parent.tmpl" %}454+ {% block body %}Hi from child. {{ super() }}{% endblock %}455+456+ # grandchild1.tmpl457+ {% extends "child.tmpl" %}458+ {% block body %}Hi from grandchild1.{% endblock %}459+460+ # grandchild2.tmpl461+ {% extends "child.tmpl" %}462+ {% block body %}Hi from grandchild2. {{ super.super() }} {% endblock %}463+464+465+Rendering ``child.tmpl`` will give466+``body: Hi from child. Hi from parent.``467+468+Rendering ``grandchild1.tmpl`` will give469+``body: Hi from grandchild1.``470+471+Rendering ``grandchild2.tmpl`` will give472+``body: Hi from grandchild2. Hi from parent.``473+474+475 Named Block End-Tags476 ~~~~~~~~~~~~~~~~~~~~477 478 Jinja2 allows you to put the name of the block after the end tag for better134 unmodified lines613 As variables in templates retain their object properties, it is possible to614 iterate over containers like `dict`::615 616 <dl>580- {% for key, value in my_dict.iteritems() %}617+ {% for key, value in my_dict.items() %}618 <dt>{{ key|e }}</dt>619 <dd>{{ value|e }}</dd>620 {% endfor %}621 </dl>615 unmodified lines1237 1238 /1239 Divide two numbers. The return value will be a floating point number.1240 ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``.1204- (Just like ``from __future__ import division``.)1241 1242 //1243 Divide two numbers and return the truncated integer result.1244 ``{{ 20 // 7 }}`` is ``2``.104 unmodified lines1349 The general syntax is ``<do something> if <something is true> else <do1350 something else>``.1351 1352 The `else` part is optional. If not provided, the else block implicitly1317-evaluates into an undefined object:1353+evaluates into an undefined object::1354 1355+ {{ ('[%s]' % page.title) if page.title }}1356+1357+1358+.. _python-methods:1359+1360+Python Methods1361+~~~~~~~~~~~~~~1362+1363+You can also use any of the methods of defined on a variable's type.1364+The value returned from the method invocation is used as the value of the expression.1365+Here is an example that uses methods defined on strings (where ``page.title`` is a string):1366+1367 .. code-block:: text1368 1321- {{ ('[%s]' % page.title) if page.title }}1369+ {{ page.title.capitalize() }}1370 1371+This also works for methods on user-defined types.1372+For example, if variable ``f`` of type ``Foo`` has a method ``bar`` defined on it,1373+you can do the following:1374 1375+.. code-block:: text1376+1377+ {{ f.bar() }}1378+1379+1380 .. _builtin-filters:1381 1382 List of Builtin Filters1383 -----------------------374 unmodified linesmodified:ext/Vim/jinja.vim+3 added
80 unmodified lines81 syn region jinjaRaw matchgroup=jinjaRawDelim start="{%\s*raw\s*%}" end="{%\s*endraw\s*%}" containedin=ALLBUT,jinjaTagBlock,jinjaVarBlock,jinjaString,jinjaComment82 83 " Jinja comments84 syn region jinjaComment matchgroup=jinjaCommentDelim start="{#" end="#}" containedin=ALLBUT,jinjaTagBlock,jinjaVarBlock,jinjaString,jinjaComment85+" help support folding for some setups86+setlocal commentstring={#%s#}87+setlocal comments=s:{#,e:#}88 89 " Block start keywords. A bit tricker. We only highlight at the start of a90 " tag block and only if the name is not followed by a comma or equals sign91 " which usually means that we have to deal with an assignment.47 unmodified linesmodified:ext/inlinegettext.py+1 added-1 removed
30 unmodified lines31 def filter_stream(self, stream):32 paren_stack = 033 34 for token in stream:35- if token.type is not 'data':35+ if token.type != 'data':36 yield token37 continue38 39 pos = 039 unmodified linesmodified:jinja2/__init__.py+2 added-2 removed
40 unmodified lines41 from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache, \42 MemcachedBytecodeCache43 44 # undefined types45-from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined, \46- make_logging_undefined45+from jinja2.runtime import Undefined, ChainableUndefined, DebugUndefined, \46+ StrictUndefined, make_logging_undefined47 48 # exceptions49 from jinja2.exceptions import TemplateError, UndefinedError, \50 TemplateNotFound, TemplatesNotFound, TemplateSyntaxError, \22 unmodified linesmodified:jinja2/bccache.py+3 added-3 removed
1 unmodified line2 """3 jinja2.bccache4 ~~~~~~~~~~~~~~5 6- This module implements the bytecode cache system Jinja is optionally7- using. This is useful if you have very complex template situations and8- the compiliation of all those templates slow down your application too6+ This module implements the bytecode cache system that Jinja optionally uses.7+ This is useful if you have very complex template situations and8+ the compilation of all those templates slows down your application too9 much.10 11 Situations where this is useful are often forking web applications that12 are initialized on the first request.350 unmodified linesmodified:jinja2/filters.py+62 added-16 removed
63 unmodified lines64 passed object with the rules of the environment. Dots are allowed65 to access attributes of attributes. Integer parts in paths are66 looked up as integers.67 """68- if attribute is None:69- attribute = []70- elif isinstance(attribute, string_types):71- attribute = [int(x) if x.isdigit() else x for x in attribute.split('.')]72- else:73- attribute = [attribute]68+ attribute = _prepare_attribute_parts(attribute)69 70 def attrgetter(item):71 for part in attribute:72 item = environment.getitem(item, part)73 74 if default and isinstance(item, Undefined):75 item = default81- break76 77 if postprocess is not None:78 item = postprocess(item)79 1 unmodified line81 82 return attrgetter83 84 85+def make_multi_attrgetter(environment, attribute, postprocess=None):86+ """Returns a callable that looks up the given comma separated87+ attributes from a passed object with the rules of the environment.88+ Dots are allowed to access attributes of each attribute. Integer89+ parts in paths are looked up as integers.90+91+ The value returned by the returned callable is a list of extracted92+ attribute values.93+94+ Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.95+ """96+ attribute_parts = attribute.split(',') if isinstance(attribute, string_types) else [attribute]97+ attribute = [_prepare_attribute_parts(attribute_part) for attribute_part in attribute_parts]98+99+ def attrgetter(item):100+ items = [None] * len(attribute)101+ for i, attribute_part in enumerate(attribute):102+ item_i = item103+ for part in attribute_part:104+ item_i = environment.getitem(item_i, part)105+106+ if postprocess is not None:107+ item_i = postprocess(item_i)108+109+ items[i] = item_i110+ return items111+112+ return attrgetter113+114+115+def _prepare_attribute_parts(attr):116+ if attr is None:117+ return []118+ elif isinstance(attr, string_types):119+ return [int(x) if x.isdigit() else x for x in attr.split('.')]120+ else:121+ return [attr]122+123+124 def do_forceescape(value):125 """Enforce HTML escaping. This will probably double escape variables."""126 if hasattr(value, '__html__'):127 value = value.__html__()178 unmodified lines306 {% endfor %}307 308 .. versionchanged:: 2.6309 The `attribute` parameter was added.310+ The attribute parameter can contain multiple comma separated311+ attributes, e.g. attr1,attr2.312 """278- key_func = make_attrgetter(313+ key_func = make_multi_attrgetter(314 environment, attribute,315 postprocess=ignore_case if not case_sensitive else None316 )317 return sorted(value, key=key_func, reverse=reverse)318 319 320 @environmentfilter321 def do_unique(environment, value, case_sensitive=False, attribute=None):287- """Returns a list of unique items from the the given iterable.322+ """Returns a list of unique items from the given iterable.323 324 .. sourcecode:: jinja325 291- {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}326+ {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}327 -> ['foo', 'bar', 'foobar']328 329 The unique items are yielded in the same order as their first occurrence in330 the iterable passed to the filter.23 unmodified lines354 except StopIteration:355 return environment.undefined('No aggregated item, sequence was empty.')356 357 key_func = make_attrgetter(323- environment, attribute,324- ignore_case if not case_sensitive else None358+ environment,359+ attribute,360+ postprocess=ignore_case if not case_sensitive else None361 )362 return func(chain([first], it), key=key_func)363 364 42 unmodified lines407 408 .. sourcecode:: jinja409 410 {{ ''|default('the string was empty', true) }}411+412+ .. versionchanged:: 2.11413+ It's now possible to configure the :class:`~jinja2.Environment` with414+ :class:`~jinja2.ChainableUndefined` to make the `default` filter work415+ on nested elements and attributes that may contain undefined values416+ in the chain without getting an :exc:`~jinja2.UndefinedError`.417 """418 if isinstance(value, Undefined) or (boolean and not value):419 return default_value420 return value343 unmodified lines764 three ul tags that represent columns:765 766 .. sourcecode:: html+jinja767 726- <div class="columwrapper">768+ <div class="columnwrapper">769 {%- for column in items|slice(3) %}770 <ul class="column-{{ loop.index }}">771 {%- for item in column %}772 <li>{{ item }}</li>233 unmodified lines1006 .. sourcecode:: jinja1007 1008 Users on this page: {{ users|map(attribute='username')|join(', ') }}1009 968- If the list of objects may not contain the given attribute, a default969- value may be provided.1010+ You can specify a ``default`` value to use if an object in the list1011+ does not have the given attribute.1012 1013 .. sourcecode:: jinja1014 973- {{ users|map(attribute='username', default='Anonymous')|join(', ') }}1015+ {{ users|map(attribute="username", default="Anonymous")|join(", ") }}1016 1017 Alternatively you can let it invoke a filter by passing the name of the1018 filter and the arguments afterwards. A good example would be applying a1019 text conversion filter on a sequence:1 unmodified line1021 .. sourcecode:: jinja1022 1023 Users on this page: {{ titles|map('lower')|join(', ') }}1024 1025+ .. versionchanged:: 2.11.01026+ Added the ``default`` parameter.1027+1028 .. versionadded:: 2.71029 """1030 seq, func = prepare_map(args, kwargs)1031 if seq:118 unmodified lines1150 1151 def prepare_map(args, kwargs):1152 context = args[0]1153 seq = args[1]1154+ default = None1155 1156 if len(args) == 2 and 'attribute' in kwargs:1157 attribute = kwargs.pop('attribute')1158 default = kwargs.pop('default', None)104 unmodified linesmodified:jinja2/lexer.py+27 added-17 removed
443 unmodified lines444 block_suffix_re = environment.trim_blocks and '\\n?' or ''445 446 # strip leading spaces if lstrip_blocks is enabled447 prefix_re = {}448+ no_lstrip_re = e('+')449+ # detect overlap between block and variable or comment strings450+ block_diff = c(r'^%s(.*)' % e(environment.block_start_string))451+ # make sure we don't mistake a block for a variable or a comment452+ m = block_diff.match(environment.comment_start_string)453+ no_lstrip_re += m and r'|%s' % e(m.group(1)) or ''454+ m = block_diff.match(environment.variable_start_string)455+ no_lstrip_re += m and r'|%s' % e(m.group(1)) or ''456+ # detect overlap between comment and variable strings457+ comment_diff = c(r'^%s(.*)' % e(environment.comment_start_string))458+ m = comment_diff.match(environment.variable_start_string)459+ no_variable_re = m and r'(?!%s)' % e(m.group(1)) or ''460+461 if environment.lstrip_blocks:462 # use '{%+' to manually disable lstrip_blocks behavior450- no_lstrip_re = e('+')451- # detect overlap between block and variable or comment strings452- block_diff = c(r'^%s(.*)' % e(environment.block_start_string))453- # make sure we don't mistake a block for a variable or a comment454- m = block_diff.match(environment.comment_start_string)455- no_lstrip_re += m and r'|%s' % e(m.group(1)) or ''456- m = block_diff.match(environment.variable_start_string)457- no_lstrip_re += m and r'|%s' % e(m.group(1)) or ''458-459- # detect overlap between comment and variable strings460- comment_diff = c(r'^%s(.*)' % e(environment.comment_start_string))461- m = comment_diff.match(environment.variable_start_string)462- no_variable_re = m and r'(?!%s)' % e(m.group(1)) or ''463-463 lstrip_re = r'^[ \t]*'464 block_prefix_re = r'%s%s(?!%s)|%s\+?' % (465 lstrip_re,466 e(environment.block_start_string),5 unmodified lines472 e(environment.comment_start_string),473 no_variable_re,474 e(environment.comment_start_string),475 )477- prefix_re['block'] = block_prefix_re478- prefix_re['comment'] = comment_prefix_re476 else:480- block_prefix_re = '%s' % e(environment.block_start_string)477+ # If lstrip_blocks is False, then '{%+' is allowed but a NOP478+ block_prefix_re = r'%s(?!%s)|%s\+?' % (479+ e(environment.block_start_string),480+ no_lstrip_re,481+ e(environment.block_start_string),482+ )483+ comment_prefix_re = r'%s%s|%s\+?' % (484+ e(environment.comment_start_string),485+ no_variable_re,486+ e(environment.comment_start_string),487+ )488 489+ prefix_re['block'] = block_prefix_re490+ prefix_re['comment'] = comment_prefix_re491+492 self.newline_sequence = environment.newline_sequence493 self.keep_trailing_newline = environment.keep_trailing_newline494 495 # global lexing rules254 unmodified linesmodified:jinja2/parser.py+3 added-1 removed
839 unmodified lines840 self.stream.current.test_any('name:else', 'name:or',841 'name:and')):842 if self.stream.current.test('name:is'):843 self.fail('You cannot chain multiple tests with is')844- args = [self.parse_primary()]844+ arg_node = self.parse_primary()845+ arg_node = self.parse_postfix(arg_node)846+ args = [arg_node]847 else:848 args = []849 node = nodes.Test(node, name, args, kwargs, dyn_args,850 dyn_kwargs, lineno=token.lineno)57 unmodified linesmodified:jinja2/runtime.py+32 added-5 removed
399 unmodified lines400 "forgot the 'recursive' modifier.")401 return self._recurse(iterable, self._recurse, self.depth0 + 1)402 403 # a nifty trick to enhance the error message if someone tried to call404- # the the loop without or with too many arguments.404+ # the loop without or with too many arguments.405 __call__ = loop406 del loop407 408 def __repr__(self):100 unmodified lines509 # will continue to not pass one), we need to perform an instance510 # check here.511 #512 # This is considered safe because an eval context is not a valid513- # argument to callables otherwise anwyays. Worst case here is513+ # argument to callables otherwise anyway. Worst case here is514 # that if no eval context is passed we fall back to the compile515 # time autoescape flag.516 if args and isinstance(args[0], EvalContext):517 autoescape = args[0].autoescape67 unmodified lines585 586 @implements_to_string587 class Undefined(object):588 """The default undefined type. This undefined type can be printed and589- iterated over, but every other access will raise an :exc:`jinja2.exceptions.UndefinedError`:589+ iterated over, but every other access will raise an :exc:`UndefinedError`:590 591 >>> foo = Undefined(name='foo')592 >>> str(foo)593 ''15 unmodified lines609 610 @internalcode611 def _fail_with_undefined_error(self, *args, **kwargs):612 """Regular callback function for undefined objects that raises an613- `jinja2.exceptions.UndefinedError` on call.613+ `UndefinedError` on call.614 """615 if self._undefined_hint is None:616 if self._undefined_obj is missing:617 hint = '%r is undefined' % self._undefined_name131 unmodified lines749 750 return LoggingUndefined751 752 753+# No @implements_to_string decorator here because __str__754+# is not overwritten from Undefined in this class.755+# This would cause a recursion error in Python 2.756+class ChainableUndefined(Undefined):757+ """An undefined that is chainable, where both758+ __getattr__ and __getitem__ return itself rather than759+ raising an :exc:`UndefinedError`:760+761+ >>> foo = ChainableUndefined(name='foo')762+ >>> str(foo.bar['baz'])763+ ''764+ >>> foo.bar['baz'] + 42765+ Traceback (most recent call last):766+ ...767+ jinja2.exceptions.UndefinedError: 'foo' is undefined768+769+ .. versionadded:: 2.11770+ """771+ __slots__ = ()772+773+ def __getattr__(self, _):774+ return self775+776+ __getitem__ = __getattr__777+778+779 @implements_to_string780 class DebugUndefined(Undefined):781 """An undefined that returns the debug info when printed.782 47 unmodified lines830 831 832 # remove remaining slots attributes, after the metaclass did the magic they833 # are unneeded and irritating as they contain wrong data for the subclasses.808-del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__834+del Undefined.__slots__, ChainableUndefined.__slots__, \835+ DebugUndefined.__slots__, StrictUndefined.__slots__modified:jinja2/utils.py+9 added
9 unmodified lines10 """11 import re12 import json13 import errno14+import warnings15 from collections import deque16 from threading import Lock17 from jinja2._compat import text_type, string_types, implements_iterator, \18 url_quote, abc438 unmodified lines457 return [x[1] for x in self.items()]458 459 def itervalue(self):460 """Iterate over all values."""461+ warnings.warn(DeprecationWarning(462+ '"itervalue()" is deprecated and will be removed in version 2.12.'463+ + ' Use "itervalues()" instead.'464+ ), stacklevel=2)465+ return self.itervalues()466+467+ def itervalues(self):468+ """Iterate over all values."""469 return iter(self.values())470 471 def keys(self):472 """Return a list of all keys ordered by most recent usage."""179 unmodified linesmodified:tests/conftest.py+43 added-1 removed
14 unmodified lines15 from jinja2.utils import have_async_gen16 from jinja2 import Environment17 18 19-def pytest_ignore_collect(path, config):19+def pytest_ignore_collect(path):20 if 'async' in path.basename and not have_async_gen:21 return True22 return False23 24 25+def pytest_configure(config):26+ '''Register custom marks for test categories.'''27+ custom_markers = [28+ 'api',29+ 'byte_code_cache',30+ 'core_tags',31+ 'debug',32+ 'escapeUrlizeTarget',33+ 'ext',34+ 'extended',35+ 'filter',36+ 'for_loop',37+ 'helpers',38+ 'if_condition',39+ 'imports',40+ 'includes',41+ 'inheritance',42+ 'lexer',43+ 'lexnparse',44+ 'loaders',45+ 'lowlevel',46+ 'lrucache',47+ 'lstripblocks',48+ 'macros',49+ 'meta',50+ 'moduleloader',51+ 'parser',52+ 'regression',53+ 'sandbox',54+ 'set',55+ 'streaming',56+ 'syntax',57+ 'test_tests',58+ 'tokenstream',59+ 'undefined',60+ 'utils',61+ 'with_',62+ ]63+ for mark in custom_markers:64+ config.addinivalue_line('markers', mark + ': test category')65+66+67 @pytest.fixture68 def env():69 '''returns a new environment.70 '''49 unmodified linesmodified:tests/test_api.py+23 added-2 removed
11 unmodified lines12 import tempfile13 import shutil14 15 import pytest16-from jinja2 import Environment, Undefined, DebugUndefined, \17- StrictUndefined, UndefinedError, meta, \16+from jinja2 import Environment, Undefined, ChainableUndefined, \17+ DebugUndefined, StrictUndefined, UndefinedError, meta, \18 is_undefined, Template, DictLoader, make_logging_undefined19 from jinja2.compiler import CodeGenerator20 from jinja2.runtime import Context21 from jinja2.utils import Cycler235 unmodified lines257 assert env.from_string('{{ not missing }}').render() == 'True'258 pytest.raises(UndefinedError,259 env.from_string('{{ missing - 1}}').render)260 261+ def test_chainable_undefined(self):262+ env = Environment(undefined=ChainableUndefined)263+ # The following tests are copied from test_default_undefined264+ assert env.from_string('{{ missing }}').render() == u''265+ assert env.from_string('{{ missing|list }}').render() == '[]'266+ assert env.from_string('{{ missing is not defined }}').render() \267+ == 'True'268+ assert env.from_string('{{ foo.missing }}').render(foo=42) == ''269+ assert env.from_string('{{ not missing }}').render() == 'True'270+ pytest.raises(UndefinedError,271+ env.from_string('{{ missing - 1}}').render)272+273+ # The following tests ensure subclass functionality works as expected274+ assert env.from_string('{{ missing.bar["baz"] }}').render() == u''275+ assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() \276+ == u'foo'277+ assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(278+ foo=42) == u'bar'279+ assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(280+ foo={'bar': 42}) == u'baz'281+282 def test_debug_undefined(self):283 env = Environment(undefined=DebugUndefined)284 assert env.from_string('{{ missing }}').render() == '{{ missing }}'285 pytest.raises(UndefinedError,76 unmodified linesmodified:tests/test_filters.py+55 added-16 removed
21 unmodified lines22 def __str__(self):23 return text_type(self.value)24 25 26+@implements_to_string27+class Magic2(object):28+ def __init__(self, value1, value2):29+ self.value1 = value130+ self.value2 = value231+32+ def __str__(self):33+ return u'(%s,%s)' % (text_type(self.value1), text_type(self.value2))34+35+36 @pytest.mark.filter37 class TestFilter(object):38 39 def test_filter_calling(self, env):386 unmodified lines426 def test_sort4(self, env):427 tmpl = env.from_string('''{{ items|sort(attribute='value')|join }}''')428 assert tmpl.render(items=map(Magic, [3, 2, 4, 1])) == '1234'429 430+ def test_sort5(self, env):431+ tmpl = env.from_string('''{{ items|sort(attribute='value.0')|join }}''')432+ assert tmpl.render(items=map(Magic, [[3], [2], [4], [1]])) == '[1][2][3][4]'433+434+ def test_sort6(self, env):435+ tmpl = env.from_string('''{{ items|sort(attribute='value1,value2')|join }}''')436+ assert (tmpl.render(items=map(437+ lambda x: Magic2(x[0], x[1]), [(3, 1), (2, 2), (2, 1), (2, 5)]))438+ == '(2,1)(2,2)(2,5)(3,1)')439+440+ def test_sort7(self, env):441+ tmpl = env.from_string('''{{ items|sort(attribute='value2,value1')|join }}''')442+ assert (tmpl.render(items=map(lambda x: Magic2(x[0], x[1]), [(3, 1), (2, 2), (2, 1), (2, 5)])) ==443+ '(2,1)(3,1)(2,2)(2,5)')444+445+ def test_sort8(self, env):446+ tmpl = env.from_string(447+ '''{{ items|sort(attribute='value1.0,value2.0')|join }}''')448+ assert (tmpl.render(items=map(449+ lambda x: Magic2(x[0], x[1]),450+ [([3], [1]), ([2], [2]), ([2], [1]), ([2], [5])]))451+ == '([2],[1])([2],[2])([2],[5])([3],[1])')452+453 def test_unique(self, env):454 t = env.from_string('{{ "".join(["b", "A", "a", "b"]|unique) }}')455 assert t.render() == "bA"456 136 unmodified lines593 ]594 tmpl = env.from_string('{{ users|map(attribute="name")|join("|") }}')595 assert tmpl.render(users=users) == 'john|jane|mike'596 564- def test_attribute_map_default(self, env):565- class User(object):566- def __init__(self, name):567- self.name = name568- class NotUser(object):569- def __init__(self, not_name):570- self.not_name = not_name571- env = Environment()572- users = [573- User('john'),574- User('jane'),575- NotUser('plant'),576- ]577- tmpl = env.from_string('{{ users|map(attribute="name", default="anonymous")|join("|") }}')578- assert tmpl.render(users=users) == 'john|jane|anonymous'579-597 def test_empty_map(self, env):598 env = Environment()599 tmpl = env.from_string('{{ none|map("upper")|list }}')600 assert tmpl.render() == '[]'601 602+ def test_map_default(self, env):603+ class Fullname(object):604+ def __init__(self, firstname, lastname):605+ self.firstname = firstname606+ self.lastname = lastname607+608+ class Firstname(object):609+ def __init__(self, firstname):610+ self.firstname = firstname611+612+ env = Environment()613+ tmpl = env.from_string(614+ '{{ users|map(attribute="lastname", default="smith")|join(", ") }}'615+ )616+ users = [617+ Fullname("john", "lennon"),618+ Fullname("jane", "edwards"),619+ Fullname("jon", None),620+ Firstname("mike")621+ ]622+ assert tmpl.render(users=users) == "lennon, edwards, None, smith"623+624 def test_simple_select(self, env):625 env = Environment()626 tmpl = env.from_string('{{ [1, 2, 3, 4, 5]|select("odd")|join("|") }}')627 assert tmpl.render() == '1|3|5'95 unmodified linesmodified:tests/test_imports.py-2 removed
137 unmodified lines138 t = test_env.from_string('{% include [x, "header"] %}')139 test_includes(t, x='missing')140 t = test_env.from_string('{% include x %}')141 test_includes(t, x='header')142- t = test_env.from_string('{% include x %}')143- test_includes(t, x='header')142 t = test_env.from_string('{% include [x] %}')143 test_includes(t, x='header')144 145 def test_include_ignoring_missing(self, test_env):33 unmodified linesmodified:tests/test_lexnparse.py+8 added
501 unmodified lines502 env = Environment(lstrip_blocks=True, trim_blocks=False)503 tmpl = env.from_string(''' {%+ if True %}\n {%+ endif %}''')504 assert tmpl.render() == " \n "505 506+ def test_lstrip_blocks_false_with_no_lstrip(self, env):507+ # Test that + is a NOP (but does not cause an error) if lstrip_blocks=False508+ env = Environment(lstrip_blocks=False, trim_blocks=False)509+ tmpl = env.from_string(''' {% if True %}\n {% endif %}''')510+ assert tmpl.render() == " \n "511+ tmpl = env.from_string(''' {%+ if True %}\n {%+ endif %}''')512+ assert tmpl.render() == " \n "513+514 def test_lstrip_endline(self, env):515 env = Environment(lstrip_blocks=True, trim_blocks=False)516 tmpl = env.from_string(517 ''' hello{% if True %}\n goodbye{% endif %}''')148 unmodified linesmodified:tests/test_regression.py+4 added
481 unmodified lines482 def test_empty_if(self, env):483 t = env.from_string('{% if foo %}{% else %}42{% endif %}')484 assert t.render(foo=False) == '42'485 486+ def test_subproperty_if(self, env):487+ t = env.from_string('{% if object1.subproperty1 is eq object2.subproperty2 %}42{% endif %}')488+ assert t.render(object1={'subproperty1': 'value'}, object2={'subproperty2': 'value'}) == '42'489+490 def test_set_and_include(self):491 env = Environment(loader=DictLoader({492 'inc': 'bar',493 'main': '{% set foo = "foo" %}{{ foo }}{% include "inc" %}'52 unmodified linesmodified:tests/test_utils.py+21 added
30 unmodified lines31 d["d"] = 432 assert len(d) == 333 assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d34 35+ def test_itervalue_deprecated(self):36+ cache = LRUCache(3)37+ cache["a"] = 138+ cache["b"] = 239+ with pytest.deprecated_call():40+ cache.itervalue()41+42+ def test_itervalues(self):43+ cache = LRUCache(3)44+ cache["b"] = 145+ cache["a"] = 246+ values = [v for v in cache.itervalues()]47+ assert len(values) == 248+ assert 1 in values49+ assert 2 in values50+51+ def test_itervalues_empty(self):52+ cache = LRUCache(2)53+ values = [v for v in cache.itervalues()]54+ assert len(values) == 055+56 def test_pickleable(self):57 cache = LRUCache(2)58 cache["foo"] = 4259 cache["bar"] = 2348 unmodified linesadded:.azure-pipelines.yml+61 added
1+trigger:2+ - master3+ - '*.x'4+5+variables:6+ vmImage: ubuntu-latest7+ python.version: 3.78+ TOXENV: py,coverage-ci9+ hasTestResults: true10+11+strategy:12+ matrix:13+ Python 3.7 Linux:14+ vmImage: ubuntu-latest15+ Python 3.7 Windows:16+ vmImage: windows-latest17+ Python 3.7 Mac:18+ vmImage: macos-latest19+ PyPy 3 Linux:20+ python.version: pypy321+ Python 3.6 Linux:22+ python.version: 3.623+ Python 3.5 Linux:24+ python.version: 3.525+ Python 2.7 Linux:26+ python.version: 2.727+ Python 2.7 Windows:28+ python.version: 2.729+ vmImage: windows-latest30+ Docs:31+ TOXENV: docs-html32+ hasTestResults: false33+34+pool:35+ vmImage: $[ variables.vmImage ]36+37+steps:38+ - task: UsePythonVersion@039+ inputs:40+ versionSpec: $(python.version)41+ displayName: Use Python $(python.version)42+43+ - script: pip --disable-pip-version-check install -U tox44+ displayName: Install tox45+46+ - script: tox -s false -- --junit-xml=test-results.xml47+ displayName: Run tox48+49+ - task: PublishTestResults@250+ inputs:51+ testResultsFiles: test-results.xml52+ testRunTitle: $(Agent.JobName)53+ condition: eq(variables['hasTestResults'], 'true')54+ displayName: Publish test results55+56+ - task: PublishCodeCoverageResults@157+ inputs:58+ codeCoverageTool: Cobertura59+ summaryFileLocation: coverage.xml60+ condition: eq(variables['hasTestResults'], 'true')61+ displayName: Publish coverage resultsdeleted:.coveragerc-11 removed
1-[run]2-branch = True3-source =4- jinja25- tests6-7-[paths]8-source =9- jinja210- .tox/*/lib/python*/site-packages/jinja211- .tox/pypy/site-packages/jinja2modified:.gitignore+1 added
8 unmodified lines9 .DS_Store10 .tox/11 .cache/12 .idea/13+env/14 venv/15 venv-*/16 .coverage17 .coverage.*2 unmodified linesdeleted:.travis.yml-46 removed
1-dist: xenial2-sudo: false3-language: python4-5-python:6- - 3.77- - 3.68- - 3.59- - 3.410- - 2.711- - pypy3.5-6.012- - pypy2.7-6.013-14-env:15- - TOXENV=py,codecov16-17-matrix:18- include:19- - python: nightly20- env: TOXENV=py21- - python: 3.622- env: TOXENV=docs-html23-24-install:25- - pip install tox26-27-script:28- - tox29-30-cache:31- - pip32-33-branches:34- only:35- - master36- - /^.*-maintenance$/37-38-notifications:39- email: false40- irc:41- channels:42- - "chat.freenode.net#pocoo"43- on_success: change44- on_failure: always45- use_notice: true46- skip_join: truemodified:CHANGES.rst+17 added-3 removed
11 unmodified lines12 - Async support is only loaded the first time an13 :class:`~environment.Environment` enables it, in order to avoid a14 slow initial import. (`#765`_)15 - Python 2.6 and 3.3 are not supported anymore.16-- The `map` filter in async mode now automatically awaits17-- Added `default` parameter for the `map` filter. (`#985`_)16+- The ``map`` filter in async mode now automatically awaits17+- Added a new ``ChainableUndefined`` class to support getitem18+ and getattr on an undefined object. (`#977`_)19+- Allow ``{%+`` syntax (with NOP behavior) when20+ ``lstrip_blocks == False`` (`#748`_)21+- Added a ``default`` parameter for the ``map`` filter. (`#557`_)22 23+.. _#557: https://github.com/pallets/jinja/issues/55724 .. _#765: https://github.com/pallets/jinja/issues/76520-.. _#985: https://github.com/pallets/jinja/pull/98525+.. _#748: https://github.com/pallets/jinja/issues/74826+.. _#977: https://github.com/pallets/jinja/issues/97727 28 29+Version 2.10.230+--------------31+32+_Unreleased_33+34+- Fix Python 3.7 deprecation warnings.35+36+37 Version 2.10.138 --------------39 40 Released 2019-04-06598 unmodified linesadded:CODE_OF_CONDUCT.md+76 added
1+# Contributor Covenant Code of Conduct2+3+## Our Pledge4+5+In the interest of fostering an open and welcoming environment, we as6+contributors and maintainers pledge to making participation in our project and7+our community a harassment-free experience for everyone, regardless of age, body8+size, disability, ethnicity, sex characteristics, gender identity and expression,9+level of experience, education, socio-economic status, nationality, personal10+appearance, race, religion, or sexual identity and orientation.11+12+## Our Standards13+14+Examples of behavior that contributes to creating a positive environment15+include:16+17+* Using welcoming and inclusive language18+* Being respectful of differing viewpoints and experiences19+* Gracefully accepting constructive criticism20+* Focusing on what is best for the community21+* Showing empathy towards other community members22+23+Examples of unacceptable behavior by participants include:24+25+* The use of sexualized language or imagery and unwelcome sexual attention or26+ advances27+* Trolling, insulting/derogatory comments, and personal or political attacks28+* Public or private harassment29+* Publishing others' private information, such as a physical or electronic30+ address, without explicit permission31+* Other conduct which could reasonably be considered inappropriate in a32+ professional setting33+34+## Our Responsibilities35+36+Project maintainers are responsible for clarifying the standards of acceptable37+behavior and are expected to take appropriate and fair corrective action in38+response to any instances of unacceptable behavior.39+40+Project maintainers have the right and responsibility to remove, edit, or41+reject comments, commits, code, wiki edits, issues, and other contributions42+that are not aligned to this Code of Conduct, or to ban temporarily or43+permanently any contributor for other behaviors that they deem inappropriate,44+threatening, offensive, or harmful.45+46+## Scope47+48+This Code of Conduct applies both within project spaces and in public spaces49+when an individual is representing the project or its community. Examples of50+representing a project or community include using an official project e-mail51+address, posting via an official social media account, or acting as an appointed52+representative at an online or offline event. Representation of a project may be53+further defined and clarified by project maintainers.54+55+## Enforcement56+57+Instances of abusive, harassing, or otherwise unacceptable behavior may be58+reported by contacting the project team at report@palletsprojects.com. All59+complaints will be reviewed and investigated and will result in a response that60+is deemed necessary and appropriate to the circumstances. The project team is61+obligated to maintain confidentiality with regard to the reporter of an incident.62+Further details of specific enforcement policies may be posted separately.63+64+Project maintainers who do not follow or enforce the Code of Conduct in good65+faith may face temporary or permanent repercussions as determined by other66+members of the project's leadership.67+68+## Attribution69+70+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,71+available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html72+73+[homepage]: https://www.contributor-covenant.org74+75+For answers to common questions about this code of conduct, see76+https://www.contributor-covenant.org/faqdeleted:LICENSE-31 removed
1-Copyright (c) 2009 by the Jinja Team, see AUTHORS for more details.2-3-Some rights reserved.4-5-Redistribution and use in source and binary forms, with or without6-modification, are permitted provided that the following conditions are7-met:8-9- * Redistributions of source code must retain the above copyright10- notice, this list of conditions and the following disclaimer.11-12- * Redistributions in binary form must reproduce the above13- copyright notice, this list of conditions and the following14- disclaimer in the documentation and/or other materials provided15- with the distribution.16-17- * The names of the contributors may not be used to endorse or18- promote products derived from this software without specific19- prior written permission.20-21-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS22-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT23-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR24-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT25-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,26-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT27-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,28-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY29-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT30-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE31-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.added:LICENSE.rst+28 added
1+Copyright 2007 Pallets2+3+Redistribution and use in source and binary forms, with or without4+modification, are permitted provided that the following conditions are5+met:6+7+1. Redistributions of source code must retain the above copyright8+ notice, this list of conditions and the following disclaimer.9+10+2. Redistributions in binary form must reproduce the above copyright11+ notice, this list of conditions and the following disclaimer in the12+ documentation and/or other materials provided with the distribution.13+14+3. Neither the name of the copyright holder nor the names of its15+ contributors may be used to endorse or promote products derived from16+ this software without specific prior written permission.17+18+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A21+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED24+TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.deleted:Makefile-21 removed
1-test:2- py.test tests --tb=short3-4-develop:5- pip install --editable .6-7-tox-test:8- @tox9-10-release:11- python scripts/make-release.py12-13-upload-docs:14- $(MAKE) -C docs html dirhtml latex15- $(MAKE) -C docs/_build/latex all-pdf16- cd docs/_build/; mv html jinja-docs; zip -r jinja-docs.zip jinja-docs; mv jinja-docs html17- scp -r docs/_build/dirhtml/* flow.srv.pocoo.org:/srv/websites/jinja.pocoo.org/docs/18- scp -r docs/_build/latex/Jinja2.pdf flow.srv.pocoo.org:/srv/websites/jinja.pocoo.org/docs/jinja-docs.pdf19- scp -r docs/_build/jinja-docs.zip flow.srv.pocoo.org:/srv/websites/jinja.pocoo.org/docs/20-21-.PHONY: testmodified:setup.cfg+15 added-4 removed
1-[bdist_wheel]2-universal = 13-1 [metadata]2 license_file = LICENSE3 4+[bdist_wheel]5+universal = true6+7 [tool:pytest]8-minversion = 3.08 testpaths = tests9+10+[coverage:run]11+branch = True12+source =13+ jinja214+ tests15+16+[coverage:paths]17+source =18+ src/jinja219+ .tox/*/lib/python*/site-packages/jinja220+ .tox/*/site-packages/jinja2modified:setup.py+1 added-1 removed
40 unmodified lines41 setup(42 name='Jinja2',43 version='2.11.dev',44 url='http://jinja.pocoo.org/',45- license='BSD',45+ license='BSD-3-Clause',46 author='Armin Ronacher',47 author_email='armin.ronacher@active-4.com',48 description='A small but fast and easy to use stand-alone template '49 'engine written in pure python.',33 unmodified linesmodified:tox.ini+16 added-20 removed
1 [tox]2 envlist =3- py{37,36,35,34,27,py3,py}3+ py{37,36,35,27,py3,py}4 docs-html5- coverage-report5+ coverage6+skip_missing_interpreters = true7 8 [testenv]8-passenv = LANG9-usedevelop = true9 deps =11- pytest>=3,<3.710 coverage11+ pytest12+commands = coverage run -p -m pytest --tb=short -Werror --basetemp={envtmpdir} {posargs}13 14-commands = coverage run -p -m pytest {posargs}15-14 [testenv:docs-html]17-deps = sphinx18-commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs docs/_build/html15+deps =16+ Sphinx17+ Pallets-Sphinx-Themes18+ sphinx-issues19+commands = sphinx-build -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html20 20-[testenv:docs-linkcheck]21-deps = sphinx22-commands = sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees docs docs/_build/linkcheck23-24-[testenv:coverage-report]21+[testenv:coverage]22 deps = coverage23 skip_install = true24 commands =25 coverage combine29- coverage report26 coverage html27+ coverage report28 32-[testenv:codecov]33-passenv = CI TRAVIS TRAVIS_*34-deps = codecov29+[testenv:coverage-ci]30+deps = coverage31 skip_install = true32 commands =33 coverage combine38- coverage report39- codecov34+ # Ignoring errors because 2.7.15 and 3.5.5 on Azure can't parse async files.35+ coverage xml --ignore-errors