Skip to content
Myr

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

31 files+580 added−214 removed

modified:docs/api.rst+6 added-3 removed
1API2===34.. module:: jinja25 :noindex:6 :synopsis: public Jinja2 API78This document describes the API to Jinja2 and not the template language. It9will be most useful as reference to those implementing the template interface
36 unmodified lines
46 template = env.get_template('mytemplate.html')4748To render it with some variables, just call the :meth:`render` method::4949 print template.render(the='variables', go='here')50 print(template.render(the='variables', go='here'))5152Using a template loader rather than passing strings to :class:`Template`53or :meth:`Environment.from_string` has multiple advantages. Besides being54a lot easier to use it also enables template inheritance.
267 unmodified lines
322unable to look up a name or access an attribute one of those objects is323created and returned. Some operations on undefined values are then allowed,324others fail.325325The closest to regular Python behavior is the `StrictUndefined` which326The closest to regular Python behavior is the :class:`StrictUndefined` which327disallows all operations beside testing if it's an undefined object.328329.. autoclass:: jinja2.Undefined()330
22 unmodified lines
353 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.356357.. autoclass:: jinja2.ChainableUndefined()358359.. autoclass:: jinja2.DebugUndefined()360361.. autoclass:: jinja2.StrictUndefined()362
473 unmodified lines
836837 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 lines
modified:docs/faq.rst+1 added-2 removed
151 unmodified lines
152153Python 2.3 is missing a lot of features that are used heavily in Jinja2. This154decision was made as with the upcoming Python 2.6 and 3.0 versions it becomes155harder to maintain the code for older Python versions. If you really need156Python 2.3 support you either have to use `Jinja 1`_ or other templating156Python 2.3 support you either have to use Jinja 1 or other templating157engines that still support 2.3.158159Python 2.4/2.5/3.1/3.2 support was removed when we switched to supporting160Python 2 and 3 by the same sourcecode (without using 2to3). It was required to
30 unmodified lines
191templates passing information to the parent template. To avoid this192issue rename the macro or variable in the parent template to have an193uncommon prefix.194195.. _Jinja 1: http://jinja.pocoo.org/1/
modified:docs/templates.rst+62 added-6 removed
393 unmodified lines
394this template "extends" another template. When the template system evaluates395this template, it first locates the parent. The extends tag should be the396first tag in the template. Everything before it is printed out normally and397may cause confusion. For details about this behavior and how to take398advantage of it, see :ref:`null-master-fallback`.398advantage of it, see :ref:`null-master-fallback`. Also a block will always be399filled in regardless of whether the surrounding condition is evaluated to be true 400or false.401402The filename of the template depends on the template loader. For example, the403:class:`FileSystemLoader` allows you to access other templates by giving the404filename. You can access templates in subdirectories with a slash::
21 unmodified lines
426427Super Blocks428~~~~~~~~~~~~429428It's possible to render the contents of the parent block by calling `super`.430It's possible to render the contents of the parent block by calling ``super()``.431This gives back the results of the parent block::432433 {% block sidebar %}434 <h3>Table Of Contents</h3>
1 unmodified line
436 {{ super() }}437 {% endblock %}438439440Nesting extends441~~~~~~~~~~~~~~~442443In the case of multiple levels of ``{% extends %}``,444``super`` references may be chained (as in ``super.super()``)445to skip levels in the inheritance tree.446447For example::448449 # parent.tmpl450 body: {% block body %}Hi from parent.{% endblock %}451452 # child.tmpl453 {% extends "parent.tmpl" %}454 {% block body %}Hi from child. {{ super() }}{% endblock %}455456 # grandchild1.tmpl457 {% extends "child.tmpl" %}458 {% block body %}Hi from grandchild1.{% endblock %}459460 # grandchild2.tmpl461 {% extends "child.tmpl" %}462 {% block body %}Hi from grandchild2. {{ super.super() }} {% endblock %}463464465Rendering ``child.tmpl`` will give466``body: Hi from child. Hi from parent.``467468Rendering ``grandchild1.tmpl`` will give469``body: Hi from grandchild1.``470471Rendering ``grandchild2.tmpl`` will give472``body: Hi from grandchild2. Hi from parent.``473474475Named Block End-Tags476~~~~~~~~~~~~~~~~~~~~477478Jinja2 allows you to put the name of the block after the end tag for better
134 unmodified lines
613As variables in templates retain their object properties, it is possible to614iterate over containers like `dict`::615616 <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 lines
12371238/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``.)12411242//1243 Divide two numbers and return the truncated integer result.1244 ``{{ 20 // 7 }}`` is ``2``.
104 unmodified lines
1349The general syntax is ``<do something> if <something is true> else <do1350something else>``.13511352The `else` part is optional. If not provided, the else block implicitly1317evaluates into an undefined object:1353evaluates into an undefined object::13541355 {{ ('[%s]' % page.title) if page.title }}135613571358.. _python-methods:13591360Python Methods1361~~~~~~~~~~~~~~13621363You can also use any of the methods of defined on a variable's type.1364The value returned from the method invocation is used as the value of the expression.1365Here is an example that uses methods defined on strings (where ``page.title`` is a string):13661367.. code-block:: text13681321 {{ ('[%s]' % page.title) if page.title }}1369 {{ page.title.capitalize() }}13701371This also works for methods on user-defined types.1372For example, if variable ``f`` of type ``Foo`` has a method ``bar`` defined on it,1373you can do the following:13741375.. code-block:: text13761377 {{ f.bar() }}137813791380.. _builtin-filters:13811382List of Builtin Filters1383-----------------------
374 unmodified lines
modified:ext/Vim/jinja.vim+3 added
80 unmodified lines
81syn region jinjaRaw matchgroup=jinjaRawDelim start="{%\s*raw\s*%}" end="{%\s*endraw\s*%}" containedin=ALLBUT,jinjaTagBlock,jinjaVarBlock,jinjaString,jinjaComment8283" Jinja comments84syn region jinjaComment matchgroup=jinjaCommentDelim start="{#" end="#}" containedin=ALLBUT,jinjaTagBlock,jinjaVarBlock,jinjaString,jinjaComment85" help support folding for some setups86setlocal commentstring={#%s#}87setlocal comments=s:{#,e:#}8889" 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 lines
modified:ext/inlinegettext.py+1 added-1 removed
30 unmodified lines
31 def filter_stream(self, stream):32 paren_stack = 03334 for token in stream:35 if token.type is not 'data':35 if token.type != 'data':36 yield token37 continue3839 pos = 0
39 unmodified lines
modified:jinja2/__init__.py+2 added-2 removed
40 unmodified lines
41from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache, \42 MemcachedBytecodeCache4344# undefined types45from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined, \46 make_logging_undefined45from jinja2.runtime import Undefined, ChainableUndefined, DebugUndefined, \46 StrictUndefined, make_logging_undefined4748# exceptions49from jinja2.exceptions import TemplateError, UndefinedError, \50 TemplateNotFound, TemplatesNotFound, TemplateSyntaxError, \
22 unmodified lines
modified:jinja2/bccache.py+3 added-3 removed
1 unmodified line
2"""3 jinja2.bccache4 ~~~~~~~~~~~~~~56 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.1011 Situations where this is useful are often forking web applications that12 are initialized on the first request.
350 unmodified lines
modified:jinja2/filters.py+62 added-16 removed
63 unmodified lines
64 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)6970 def attrgetter(item):71 for part in attribute:72 item = environment.getitem(item, part)7374 if default and isinstance(item, Undefined):75 item = default81 break7677 if postprocess is not None:78 item = postprocess(item)79
1 unmodified line
8182 return attrgetter838485def 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.9091 The value returned by the returned callable is a list of extracted92 attribute values.9394 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]9899 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)105106 if postprocess is not None:107 item_i = postprocess(item_i)108109 items[i] = item_i110 return items111112 return attrgetter113114115def _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]122123124def do_forceescape(value):125 """Enforce HTML escaping. This will probably double escape variables."""126 if hasattr(value, '__html__'):127 value = value.__html__()
178 unmodified lines
306 {% endfor %}307308 .. 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)318319320@environmentfilter321def 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.323324 .. sourcecode:: jinja325291 {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}326 {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}327 -> ['foo', 'bar', 'foobar']328329 The unique items are yielded in the same order as their first occurrence in330 the iterable passed to the filter.
23 unmodified lines
354 except StopIteration:355 return environment.undefined('No aggregated item, sequence was empty.')356357 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)363364
42 unmodified lines
407408 .. sourcecode:: jinja409410 {{ ''|default('the string was empty', true) }}411412 .. 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 value
343 unmodified lines
764 three ul tags that represent columns:765766 .. sourcecode:: html+jinja767726 <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 lines
1006 .. sourcecode:: jinja10071008 Users on this page: {{ users|map(attribute='username')|join(', ') }}1009968 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.10121013 .. sourcecode:: jinja1014973 {{ users|map(attribute='username', default='Anonymous')|join(', ') }}1015 {{ users|map(attribute="username", default="Anonymous")|join(", ") }}10161017 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 line
1021 .. sourcecode:: jinja10221023 Users on this page: {{ titles|map('lower')|join(', ') }}10241025 .. versionchanged:: 2.11.01026 Added the ``default`` parameter.10271028 .. versionadded:: 2.71029 """1030 seq, func = prepare_map(args, kwargs)1031 if seq:
118 unmodified lines
11501151def prepare_map(args, kwargs):1152 context = args[0]1153 seq = args[1]1154 default = None11551156 if len(args) == 2 and 'attribute' in kwargs:1157 attribute = kwargs.pop('attribute')1158 default = kwargs.pop('default', None)
104 unmodified lines
modified:jinja2/lexer.py+27 added-17 removed
443 unmodified lines
444 block_suffix_re = environment.trim_blocks and '\\n?' or ''445446 # 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 ''460461 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 ''458459 # 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 ''463463 lstrip_re = r'^[ \t]*'464 block_prefix_re = r'%s%s(?!%s)|%s\+?' % (465 lstrip_re,466 e(environment.block_start_string),
5 unmodified lines
472 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 )488489 prefix_re['block'] = block_prefix_re490 prefix_re['comment'] = comment_prefix_re491492 self.newline_sequence = environment.newline_sequence493 self.keep_trailing_newline = environment.keep_trailing_newline494495 # global lexing rules
254 unmodified lines
modified:jinja2/parser.py+3 added-1 removed
839 unmodified lines
840 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 lines
modified:jinja2/runtime.py+32 added-5 removed
399 unmodified lines
400 "forgot the 'recursive' modifier.")401 return self._recurse(iterable, self._recurse, self.depth0 + 1)402403 # 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 loop407408 def __repr__(self):
100 unmodified lines
509 # 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].autoescape
67 unmodified lines
585586@implements_to_string587class 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`:590591 >>> foo = Undefined(name='foo')592 >>> str(foo)593 ''
15 unmodified lines
609610 @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_name
131 unmodified lines
749750 return LoggingUndefined751752753# 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.756class ChainableUndefined(Undefined):757 """An undefined that is chainable, where both758 __getattr__ and __getitem__ return itself rather than759 raising an :exc:`UndefinedError`:760761 >>> 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 undefined768769 .. versionadded:: 2.11770 """771 __slots__ = ()772773 def __getattr__(self, _):774 return self775776 __getitem__ = __getattr__777778779@implements_to_string780class DebugUndefined(Undefined):781 """An undefined that returns the debug info when printed.782
47 unmodified lines
830831832# remove remaining slots attributes, after the metaclass did the magic they833# are unneeded and irritating as they contain wrong data for the subclasses.808del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__834del Undefined.__slots__, ChainableUndefined.__slots__, \835 DebugUndefined.__slots__, StrictUndefined.__slots__
modified:jinja2/utils.py+9 added
9 unmodified lines
10"""11import re12import json13import errno14import warnings15from collections import deque16from threading import Lock17from jinja2._compat import text_type, string_types, implements_iterator, \18 url_quote, abc
438 unmodified lines
457 return [x[1] for x in self.items()]458459 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()466467 def itervalues(self):468 """Iterate over all values."""469 return iter(self.values())470471 def keys(self):472 """Return a list of all keys ordered by most recent usage."""
179 unmodified lines
modified:tests/conftest.py+43 added-1 removed
14 unmodified lines
15from jinja2.utils import have_async_gen16from jinja2 import Environment171819def pytest_ignore_collect(path, config):19def pytest_ignore_collect(path):20 if 'async' in path.basename and not have_async_gen:21 return True22 return False232425def 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')656667@pytest.fixture68def env():69 '''returns a new environment.70 '''
49 unmodified lines
modified:tests/test_api.py+23 added-2 removed
11 unmodified lines
12import tempfile13import shutil1415import pytest16from jinja2 import Environment, Undefined, DebugUndefined, \17 StrictUndefined, UndefinedError, meta, \16from jinja2 import Environment, Undefined, ChainableUndefined, \17 DebugUndefined, StrictUndefined, UndefinedError, meta, \18 is_undefined, Template, DictLoader, make_logging_undefined19from jinja2.compiler import CodeGenerator20from jinja2.runtime import Context21from jinja2.utils import Cycler
235 unmodified lines
257 assert env.from_string('{{ not missing }}').render() == 'True'258 pytest.raises(UndefinedError,259 env.from_string('{{ missing - 1}}').render)260261 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)272273 # 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'281282 def test_debug_undefined(self):283 env = Environment(undefined=DebugUndefined)284 assert env.from_string('{{ missing }}').render() == '{{ missing }}'285 pytest.raises(UndefinedError,
76 unmodified lines
modified:tests/test_filters.py+55 added-16 removed
21 unmodified lines
22 def __str__(self):23 return text_type(self.value)242526@implements_to_string27class Magic2(object):28 def __init__(self, value1, value2):29 self.value1 = value130 self.value2 = value23132 def __str__(self):33 return u'(%s,%s)' % (text_type(self.value1), text_type(self.value2))343536@pytest.mark.filter37class TestFilter(object):3839 def test_filter_calling(self, env):
386 unmodified lines
426 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'429430 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]'433434 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)')439440 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)')444445 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])')452453 def test_unique(self, env):454 t = env.from_string('{{ "".join(["b", "A", "a", "b"]|unique) }}')455 assert t.render() == "bA"456
136 unmodified lines
593 ]594 tmpl = env.from_string('{{ users|map(attribute="name")|join("|") }}')595 assert tmpl.render(users=users) == 'john|jane|mike'596564 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'579597 def test_empty_map(self, env):598 env = Environment()599 tmpl = env.from_string('{{ none|map("upper")|list }}')600 assert tmpl.render() == '[]'601602 def test_map_default(self, env):603 class Fullname(object):604 def __init__(self, firstname, lastname):605 self.firstname = firstname606 self.lastname = lastname607608 class Firstname(object):609 def __init__(self, firstname):610 self.firstname = firstname611612 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"623624 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 lines
modified:tests/test_imports.py-2 removed
137 unmodified lines
138 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')144145 def test_include_ignoring_missing(self, test_env):
33 unmodified lines
modified:tests/test_lexnparse.py+8 added
501 unmodified lines
502 env = Environment(lstrip_blocks=True, trim_blocks=False)503 tmpl = env.from_string(''' {%+ if True %}\n {%+ endif %}''')504 assert tmpl.render() == " \n "505506 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 "513514 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 lines
modified:tests/test_regression.py+4 added
481 unmodified lines
482 def test_empty_if(self, env):483 t = env.from_string('{% if foo %}{% else %}42{% endif %}')484 assert t.render(foo=False) == '42'485486 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'489490 def test_set_and_include(self):491 env = Environment(loader=DictLoader({492 'inc': 'bar',493 'main': '{% set foo = "foo" %}{{ foo }}{% include "inc" %}'
52 unmodified lines
modified:tests/test_utils.py+21 added
30 unmodified lines
31 d["d"] = 432 assert len(d) == 333 assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d3435 def test_itervalue_deprecated(self):36 cache = LRUCache(3)37 cache["a"] = 138 cache["b"] = 239 with pytest.deprecated_call():40 cache.itervalue()4142 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 values5051 def test_itervalues_empty(self):52 cache = LRUCache(2)53 values = [v for v in cache.itervalues()]54 assert len(values) == 05556 def test_pickleable(self):57 cache = LRUCache(2)58 cache["foo"] = 4259 cache["bar"] = 23
48 unmodified lines
added:.azure-pipelines.yml+61 added
1trigger:2 - master3 - '*.x'45variables:6 vmImage: ubuntu-latest7 python.version: 3.78 TOXENV: py,coverage-ci9 hasTestResults: true1011strategy: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: false3334pool:35 vmImage: $[ variables.vmImage ]3637steps:38 - task: UsePythonVersion@039 inputs:40 versionSpec: $(python.version)41 displayName: Use Python $(python.version)4243 - script: pip --disable-pip-version-check install -U tox44 displayName: Install tox4546 - script: tox -s false -- --junit-xml=test-results.xml47 displayName: Run tox4849 - task: PublishTestResults@250 inputs:51 testResultsFiles: test-results.xml52 testRunTitle: $(Agent.JobName)53 condition: eq(variables['hasTestResults'], 'true')54 displayName: Publish test results5556 - task: PublishCodeCoverageResults@157 inputs:58 codeCoverageTool: Cobertura59 summaryFileLocation: coverage.xml60 condition: eq(variables['hasTestResults'], 'true')61 displayName: Publish coverage results
deleted:.coveragerc-11 removed
1[run]2branch = True3source =4 jinja25 tests67[paths]8source =9 jinja210 .tox/*/lib/python*/site-packages/jinja211 .tox/pypy/site-packages/jinja2
modified:.gitignore+1 added
8 unmodified lines
9.DS_Store10.tox/11.cache/12.idea/13env/14venv/15venv-*/16.coverage17.coverage.*
2 unmodified lines
deleted:.travis.yml-46 removed
1dist: xenial2sudo: false3language: python45python:6 - 3.77 - 3.68 - 3.59 - 3.410 - 2.711 - pypy3.5-6.012 - pypy2.7-6.01314env:15 - TOXENV=py,codecov1617matrix:18 include:19 - python: nightly20 env: TOXENV=py21 - python: 3.622 env: TOXENV=docs-html2324install:25 - pip install tox2627script:28 - tox2930cache:31 - pip3233branches:34 only:35 - master36 - /^.*-maintenance$/3738notifications:39 email: false40 irc:41 channels:42 - "chat.freenode.net#pocoo"43 on_success: change44 on_failure: always45 use_notice: true46 skip_join: true
modified:CHANGES.rst+17 added-3 removed
11 unmodified lines
12- 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`_)2223.. _#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/977272829Version 2.10.230--------------3132_Unreleased_3334- Fix Python 3.7 deprecation warnings.353637Version 2.10.138--------------3940Released 2019-04-06
598 unmodified lines
added:CODE_OF_CONDUCT.md+76 added
1# Contributor Covenant Code of Conduct23## Our Pledge45In the interest of fostering an open and welcoming environment, we as6contributors and maintainers pledge to making participation in our project and7our community a harassment-free experience for everyone, regardless of age, body8size, disability, ethnicity, sex characteristics, gender identity and expression,9level of experience, education, socio-economic status, nationality, personal10appearance, race, religion, or sexual identity and orientation.1112## Our Standards1314Examples of behavior that contributes to creating a positive environment15include:1617* 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 members2223Examples of unacceptable behavior by participants include:2425* 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 setting3334## Our Responsibilities3536Project maintainers are responsible for clarifying the standards of acceptable37behavior and are expected to take appropriate and fair corrective action in38response to any instances of unacceptable behavior.3940Project maintainers have the right and responsibility to remove, edit, or41reject comments, commits, code, wiki edits, issues, and other contributions42that are not aligned to this Code of Conduct, or to ban temporarily or43permanently any contributor for other behaviors that they deem inappropriate,44threatening, offensive, or harmful.4546## Scope4748This Code of Conduct applies both within project spaces and in public spaces49when an individual is representing the project or its community. Examples of50representing a project or community include using an official project e-mail51address, posting via an official social media account, or acting as an appointed52representative at an online or offline event. Representation of a project may be53further defined and clarified by project maintainers.5455## Enforcement5657Instances of abusive, harassing, or otherwise unacceptable behavior may be58reported by contacting the project team at report@palletsprojects.com. All59complaints will be reviewed and investigated and will result in a response that60is deemed necessary and appropriate to the circumstances. The project team is61obligated to maintain confidentiality with regard to the reporter of an incident.62Further details of specific enforcement policies may be posted separately.6364Project maintainers who do not follow or enforce the Code of Conduct in good65faith may face temporary or permanent repercussions as determined by other66members of the project's leadership.6768## Attribution6970This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,71available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html7273[homepage]: https://www.contributor-covenant.org7475For answers to common questions about this code of conduct, see76https://www.contributor-covenant.org/faq
deleted:LICENSE-31 removed
1Copyright (c) 2009 by the Jinja Team, see AUTHORS for more details.23Some rights reserved.45Redistribution and use in source and binary forms, with or without6modification, are permitted provided that the following conditions are7met:89 * Redistributions of source code must retain the above copyright10 notice, this list of conditions and the following disclaimer.1112 * 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.1617 * The names of the contributors may not be used to endorse or18 promote products derived from this software without specific19 prior written permission.2021THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS22"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT23LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR24A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT25OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,26SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT27LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,28DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY29THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT30(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE31OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
added:LICENSE.rst+28 added
1Copyright 2007 Pallets23Redistribution and use in source and binary forms, with or without4modification, are permitted provided that the following conditions are5met:671. Redistributions of source code must retain the above copyright8 notice, this list of conditions and the following disclaimer.9102. 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.13143. 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.1718THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A21PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED24TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
deleted:Makefile-21 removed
1test:2 py.test tests --tb=short34develop:5 pip install --editable .67tox-test:8 @tox910release:11 python scripts/make-release.py1213upload-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/2021.PHONY: test
modified:setup.cfg+15 added-4 removed
1[bdist_wheel]2universal = 131[metadata]2license_file = LICENSE34[bdist_wheel]5universal = true67[tool:pytest]8minversion = 3.08testpaths = tests910[coverage:run]11branch = True12source =13 jinja214 tests1516[coverage:paths]17source =18 src/jinja219 .tox/*/lib/python*/site-packages/jinja220 .tox/*/site-packages/jinja2
modified:setup.py+1 added-1 removed
40 unmodified lines
41setup(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 lines
modified:tox.ini+16 added-20 removed
1[tox]2envlist =3 py{37,36,35,34,27,py3,py}3 py{37,36,35,27,py3,py}4 docs-html5 coverage-report5 coverage6skip_missing_interpreters = true78[testenv]8passenv = LANG9usedevelop = true9deps =11 pytest>=3,<3.710 coverage11 pytest12commands = coverage run -p -m pytest --tb=short -Werror --basetemp={envtmpdir} {posargs}1314commands = coverage run -p -m pytest {posargs}1514[testenv:docs-html]17deps = sphinx18commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs docs/_build/html15deps =16 Sphinx17 Pallets-Sphinx-Themes18 sphinx-issues19commands = sphinx-build -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html2020[testenv:docs-linkcheck]21deps = sphinx22commands = sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees docs docs/_build/linkcheck2324[testenv:coverage-report]21[testenv:coverage]22deps = coverage23skip_install = true24commands =25 coverage combine29 coverage report26 coverage html27 coverage report2832[testenv:codecov]33passenv = CI TRAVIS TRAVIS_*34deps = codecov29[testenv:coverage-ci]30deps = coverage31skip_install = true32commands =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