Add previtem/nextitem to loop context
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Adrian Moennich · committed by Adrian Moennich · parent edac1a8 · Browse files · 7 files·+95 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- related: #641
Diff stats
7 files+95 added−13 removed
- tests:+40 added−0 removed
- other:+55 added−13 removed
Provenance
- Commit
9bdb547- Tree
696ab0d- Author
Adrian Moennich <adrian@planetcoding.net>- Committer
Adrian Moennich <adrian@planetcoding.net>- Parent
edac1a8
7 files changed+95 added−13 removed
modified:docs/templates.rst+20 added
610 unmodified lines611 +-----------------------+---------------------------------------------------+612 | `loop.depth0` | Indicates how deep in a recursive loop |613 | | the rendering currently is. Starts at level 0 |614 +-----------------------+---------------------------------------------------+615+| `loop.previtem` | The item from the previous iteration of the loop. |616+| | Undefined during the first iteration. |617++-----------------------+---------------------------------------------------+618+| `loop.nextitem` | The item from the following iteration of the loop.|619+| | Undefined during the last iteration. |620++-----------------------+---------------------------------------------------+621 622 Within a for-loop, it's possible to cycle among a list of strings/variables623 each time through the loop by using the special `loop.cycle` helper::624 60 unmodified lines685 a bug where in some circumstances it appeared that assignments would work.686 This is not supported. See :ref:`assignments` for more information about687 how to deal with this.688 689+If all you want to do is check whether some value has changed since the690+last iteration or will change in the next iteration, you can use `previtem`691+and `nextitem`::692+693+ {% for value in values %}694+ {% if loop.previtem is defined and value > loop.previtem %}695+ The value just increased!696+ {% endif %}697+ {{ value }}698+ {% if loop.nextitem is defined and loop.nextitem > value %}699+ The value will increase even more!700+ {% endif %}701+ {% endfor %}702+703 .. _if:704 705 If706 ~~880 unmodified linesmodified:jinja2/asyncsupport.py+8 added-6 removed
187 unmodified lines188 189 190 class AsyncLoopContext(LoopContextBase):191 192- def __init__(self, async_iterator, after, length, recurse=None,192+ def __init__(self, async_iterator, undefined, after, length, recurse=None,193 depth0=0):194- LoopContextBase.__init__(self, recurse, depth0)194+ LoopContextBase.__init__(self, undefined, recurse, depth0)195 self._async_iterator = async_iterator196 self._after = after197 self._length = length198 21 unmodified lines220 ctx = self.context221 ctx.index0 += 1222 if ctx._after is _last_iteration:223 raise StopAsyncIteration()224- next_elem = ctx._after224+ ctx._before = ctx._current225+ ctx._current = ctx._after226 try:227 ctx._after = await ctx._async_iterator.__anext__()228 except StopAsyncIteration:229 ctx._after = _last_iteration229- return next_elem, ctx230+ return ctx._current, ctx231 232 232-async def make_async_loop_context(iterable, recurse=None, depth0=0):233+async def make_async_loop_context(iterable, undefined, recurse=None, depth0=0):234 # Length is more complicated and less efficient in async mode. The235 # reason for this is that we cannot know if length will be used236 # upfront but because length is a property we cannot lazily execute it237 # later. This means that we need to buffer it up and measure :(13 unmodified lines251 try:252 after = await async_iterator.__anext__()253 except StopAsyncIteration:254 after = _last_iteration254- return AsyncLoopContext(async_iterator, after, length, recurse, depth0)255+ return AsyncLoopContext(async_iterator, undefined, after, length, recurse,256+ depth0)modified:jinja2/compiler.py+2 added-2 removed
1110 unmodified lines1111 if node.test:1112 self.write(')')1113 1114 if node.recursive:1115- self.write(', loop_render_func, depth):')1115+ self.write(', undefined, loop_render_func, depth):')1116 else:1117- self.write(extended_loop and '):' or ':')1117+ self.write(extended_loop and ', undefined):' or ':')1118 1119 self.indent()1120 self.enter_frame(loop_frame)1121 576 unmodified linesmodified:jinja2/runtime.py+22 added-5 removed
34 unmodified lines35 36 #: the identity function. Useful for certain things in the environment37 identity = lambda x: x38 39+_first_iteration = object()40 _last_iteration = object()41 42 43 def markup_join(seq):305 unmodified lines349 350 class LoopContextBase(object):351 """A loop context for dynamic iteration."""352 353+ _before = _first_iteration354+ _current = _first_iteration355 _after = _last_iteration356 _length = None357 355- def __init__(self, recurse=None, depth0=0):358+ def __init__(self, undefined, recurse=None, depth0=0):359+ self._undefined = undefined360 self._recurse = recurse361 self.index0 = -1362 self.depth0 = depth0363 9 unmodified lines373 revindex = property(lambda x: x.length - x.index0)374 revindex0 = property(lambda x: x.length - x.index)375 depth = property(lambda x: x.depth0 + 1)376 377+ @property378+ def previtem(self):379+ if self._before is _first_iteration:380+ return self._undefined('there is no previous item')381+ return self._before382+383+ @property384+ def nextitem(self):385+ if self._after is _last_iteration:386+ return self._undefined('there is no next item')387+ return self._after388+389 def __len__(self):390 return self.length391 392 @internalcode17 unmodified lines410 411 412 class LoopContext(LoopContextBase):413 398- def __init__(self, iterable, recurse=None, depth0=0):399- LoopContextBase.__init__(self, recurse, depth0)414+ def __init__(self, iterable, undefined, recurse=None, depth0=0):415+ LoopContextBase.__init__(self, undefined, recurse, depth0)416 self._iterator = iter(iterable)417 418 # try to get the length of the iterable early. This must be done419 # here because there are some broken iterators around where there43 unmodified lines463 ctx = self.context464 ctx.index0 += 1465 if ctx._after is _last_iteration:466 raise StopIteration()451- next_elem = ctx._after467+ ctx._before = ctx._current468+ ctx._current = ctx._after469 ctx._after = ctx._safe_next()453- return next_elem, ctx470+ return ctx._current, ctx471 472 473 class Macro(object):474 """Wraps a macro function."""330 unmodified linesmodified:tests/test_async.py+20 added
302 unmodified lines303 for item in seq %}{{ loop.cycle(*through) }}{% endfor %}''')304 output = tmpl.render(seq=list(range(4)), through=('<1>', '<2>'))305 assert output == '<1><2>' * 4306 307+ def test_lookaround(self, test_env_async):308+ tmpl = test_env_async.from_string('''{% for item in seq -%}309+ {{ loop.previtem|default('x') }}-{{ item }}-{{310+ loop.nextitem|default('x') }}|311+ {%- endfor %}''')312+ output = tmpl.render(seq=list(range(4)))313+ assert output == 'x-0-1|0-1-2|1-2-3|2-3-x|'314+315 def test_scope(self, test_env_async):316 tmpl = test_env_async.from_string('{% for item in seq %}{% endfor %}{{ item }}')317 output = tmpl.render(seq=list(range(10)))318 assert not output19 unmodified lines338 dict(a=2, b=[dict(a=1), dict(a=2)]),339 dict(a=3, b=[dict(a='a')])340 ]) == '[1<[1][2]>][2<[1][2]>][3<[a]>]'341 342+ def test_recursive_lookaround(self, test_env_async):343+ tmpl = test_env_async.from_string('''{% for item in seq recursive -%}344+ [{{ loop.previtem.a if loop.previtem is defined else 'x' }}.{{345+ item.a }}.{{ loop.nextitem.a if loop.nextitem is defined else 'x'346+ }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]347+ {%- endfor %}''')348+ assert tmpl.render(seq=[349+ dict(a=1, b=[dict(a=1), dict(a=2)]),350+ dict(a=2, b=[dict(a=1), dict(a=2)]),351+ dict(a=3, b=[dict(a='a')])352+ ]) == '[x.1.2<[x.1.2][1.2.x]>][1.2.3<[x.1.2][1.2.x]>][2.3.x<[x.a.x]>]'353+354 def test_recursive_depth0(self, test_env_async):355 tmpl = test_env_async.from_string('''{% for item in seq recursive -%}356 [{{ loop.depth0 }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]357 {%- endfor %}''')148 unmodified linesmodified:tests/test_core_tags.py+20 added
66 unmodified lines67 for item in seq %}{{ loop.cycle(*through) }}{% endfor %}''')68 output = tmpl.render(seq=list(range(4)), through=('<1>', '<2>'))69 assert output == '<1><2>' * 470 71+ def test_lookaround(self, env):72+ tmpl = env.from_string('''{% for item in seq -%}73+ {{ loop.previtem|default('x') }}-{{ item }}-{{74+ loop.nextitem|default('x') }}|75+ {%- endfor %}''')76+ output = tmpl.render(seq=list(range(4)))77+ assert output == 'x-0-1|0-1-2|1-2-3|2-3-x|'78+79 def test_scope(self, env):80 tmpl = env.from_string('{% for item in seq %}{% endfor %}{{ item }}')81 output = tmpl.render(seq=list(range(10)))82 assert not output19 unmodified lines102 dict(a=2, b=[dict(a=1), dict(a=2)]),103 dict(a=3, b=[dict(a='a')])104 ]) == '[1<[1][2]>][2<[1][2]>][3<[a]>]'105 106+ def test_recursive_lookaround(self, env):107+ tmpl = env.from_string('''{% for item in seq recursive -%}108+ [{{ loop.previtem.a if loop.previtem is defined else 'x' }}.{{109+ item.a }}.{{ loop.nextitem.a if loop.nextitem is defined else 'x'110+ }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]111+ {%- endfor %}''')112+ assert tmpl.render(seq=[113+ dict(a=1, b=[dict(a=1), dict(a=2)]),114+ dict(a=2, b=[dict(a=1), dict(a=2)]),115+ dict(a=3, b=[dict(a='a')])116+ ]) == '[x.1.2<[x.1.2][1.2.x]>][1.2.3<[x.1.2][1.2.x]>][2.3.x<[x.a.x]>]'117+118 def test_recursive_depth0(self, env):119 tmpl = env.from_string('''{% for item in seq recursive -%}120 [{{ loop.depth0 }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]121 {%- endfor %}''')287 unmodified linesmodified:CHANGES+3 added
8 unmodified lines9 create an unoptimized scope that will look up all variables from a10 derived context.11 - Added an `in` test that works like the in operator. This can be used12 in combination with `reject` and `select`.13+- Added `previtem` and `nextitem` to loop contexts, providing access to the14+ previous/next item in the loop. If such an item does not exist, the value is15+ undefined.16 17 Version 2.9.618 -------------19 (bugfix release, released on April 3rd 2017)504 unmodified lines