Merge pull request #676 from ThiefMaster/loop-lookarounds
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add previtem/nextitem/changed() to loop context
authored by Adrian · committed by GitHub · parents bec0065, bc076b3 · Browse files · 8 files·+134 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+134 added−13 removed
- tests:+54 added−0 removed
- other:+80 added−13 removed
Provenance
- Commit
b73cb48- Tree
762d8f6- Author
Adrian <adrian@planetcoding.net>- Committer
GitHub <noreply@github.com>- Parent 1
bec0065- Parent 2
bc076b3
8 files changed+134 added−13 removed
modified:docs/templates.rst+33 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+| `loop.changed(*val)` | True if previously called with a different value |622+| | (or not called at all). |623++-----------------------+---------------------------------------------------+624 625 Within a for-loop, it's possible to cycle among a list of strings/variables626 each time through the loop by using the special `loop.cycle` helper::627 60 unmodified lines688 a bug where in some circumstances it appeared that assignments would work.689 This is not supported. See :ref:`assignments` for more information about690 how to deal with this.691 692+If all you want to do is check whether some value has changed since the693+last iteration or will change in the next iteration, you can use `previtem`694+and `nextitem`::695+696+ {% for value in values %}697+ {% if loop.previtem is defined and value > loop.previtem %}698+ The value just increased!699+ {% endif %}700+ {{ value }}701+ {% if loop.nextitem is defined and loop.nextitem > value %}702+ The value will increase even more!703+ {% endif %}704+ {% endfor %}705+706+If you only care whether the value changed at all, using `changed` is even707+easier::708+709+ {% for entry in entries %}710+ {% if loop.changed(entry.category) %}711+ <h2>{{ entry.category }}</h2>712+ {% endif %}713+ <p>{{ entry.message }}</p>714+ {% endfor %}715+716 .. _if:717 718 If719 ~~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+30 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+ self._last_checked_value = missing364 365 def cycle(self, *args):366 """Cycles among the arguments with the current loop index."""367 if not args:368 raise TypeError('no items for cycling given')369 return args[self.index0 % len(args)]370 371+ def changed(self, *value):372+ """Checks whether the value has changed since the last call."""373+ if self._last_checked_value != value:374+ self._last_checked_value = value375+ return True376+ return False377+378 first = property(lambda x: x.index0 == 0)379 last = property(lambda x: x._after is _last_iteration)380 index = property(lambda x: x.index0 + 1)381 revindex = property(lambda x: x.length - x.index0)382 revindex0 = property(lambda x: x.length - x.index)383 depth = property(lambda x: x.depth0 + 1)384 385+ @property386+ def previtem(self):387+ if self._before is _first_iteration:388+ return self._undefined('there is no previous item')389+ return self._before390+391+ @property392+ def nextitem(self):393+ if self._after is _last_iteration:394+ return self._undefined('there is no next item')395+ return self._after396+397 def __len__(self):398 return self.length399 400 @internalcode17 unmodified lines418 419 420 class LoopContext(LoopContextBase):421 398- def __init__(self, iterable, recurse=None, depth0=0):399- LoopContextBase.__init__(self, recurse, depth0)422+ def __init__(self, iterable, undefined, recurse=None, depth0=0):423+ LoopContextBase.__init__(self, undefined, recurse, depth0)424 self._iterator = iter(iterable)425 426 # try to get the length of the iterable early. This must be done427 # here because there are some broken iterators around where there43 unmodified lines471 ctx = self.context472 ctx.index0 += 1473 if ctx._after is _last_iteration:474 raise StopIteration()451- next_elem = ctx._after475+ ctx._before = ctx._current476+ ctx._current = ctx._after477 ctx._after = ctx._safe_next()453- return next_elem, ctx478+ return ctx._current, ctx479 480 481 class Macro(object):482 """Wraps a macro function."""330 unmodified linesmodified:tests/test_async.py+27 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_changed(self, test_env_async):316+ tmpl = test_env_async.from_string('''{% for item in seq -%}317+ {{ loop.changed(item) }},318+ {%- endfor %}''')319+ output = tmpl.render(seq=[None, None, 1, 2, 2, 3, 4, 4, 4])320+ assert output == 'True,False,True,True,False,True,True,False,False,'321+322 def test_scope(self, test_env_async):323 tmpl = test_env_async.from_string('{% for item in seq %}{% endfor %}{{ item }}')324 output = tmpl.render(seq=list(range(10)))325 assert not output19 unmodified lines345 dict(a=2, b=[dict(a=1), dict(a=2)]),346 dict(a=3, b=[dict(a='a')])347 ]) == '[1<[1][2]>][2<[1][2]>][3<[a]>]'348 349+ def test_recursive_lookaround(self, test_env_async):350+ tmpl = test_env_async.from_string('''{% for item in seq recursive -%}351+ [{{ loop.previtem.a if loop.previtem is defined else 'x' }}.{{352+ item.a }}.{{ loop.nextitem.a if loop.nextitem is defined else 'x'353+ }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]354+ {%- endfor %}''')355+ assert tmpl.render(seq=[356+ dict(a=1, b=[dict(a=1), dict(a=2)]),357+ dict(a=2, b=[dict(a=1), dict(a=2)]),358+ dict(a=3, b=[dict(a='a')])359+ ]) == '[x.1.2<[x.1.2][1.2.x]>][1.2.3<[x.1.2][1.2.x]>][2.3.x<[x.a.x]>]'360+361 def test_recursive_depth0(self, test_env_async):362 tmpl = test_env_async.from_string('''{% for item in seq recursive -%}363 [{{ loop.depth0 }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]364 {%- endfor %}''')148 unmodified linesmodified:tests/test_core_tags.py+27 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_changed(self, env):80+ tmpl = env.from_string('''{% for item in seq -%}81+ {{ loop.changed(item) }},82+ {%- endfor %}''')83+ output = tmpl.render(seq=[None, None, 1, 2, 2, 3, 4, 4, 4])84+ assert output == 'True,False,True,True,False,True,True,False,False,'85+86 def test_scope(self, env):87 tmpl = env.from_string('{% for item in seq %}{% endfor %}{{ item }}')88 output = tmpl.render(seq=list(range(10)))89 assert not output19 unmodified lines109 dict(a=2, b=[dict(a=1), dict(a=2)]),110 dict(a=3, b=[dict(a='a')])111 ]) == '[1<[1][2]>][2<[1][2]>][3<[a]>]'112 113+ def test_recursive_lookaround(self, env):114+ tmpl = env.from_string('''{% for item in seq recursive -%}115+ [{{ loop.previtem.a if loop.previtem is defined else 'x' }}.{{116+ item.a }}.{{ loop.nextitem.a if loop.nextitem is defined else 'x'117+ }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]118+ {%- endfor %}''')119+ assert tmpl.render(seq=[120+ dict(a=1, b=[dict(a=1), dict(a=2)]),121+ dict(a=2, b=[dict(a=1), dict(a=2)]),122+ dict(a=3, b=[dict(a='a')])123+ ]) == '[x.1.2<[x.1.2][1.2.x]>][1.2.3<[x.1.2][1.2.x]>][2.3.x<[x.a.x]>]'124+125 def test_recursive_depth0(self, env):126 tmpl = env.from_string('''{% for item in seq recursive -%}127 [{{ loop.depth0 }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]128 {%- endfor %}''')287 unmodified linesmodified:AUTHORS+1 added
15 unmodified lines16 - Mickaël Guérin <kael@crocobox.org>17 - Cameron Knight18 - Lawrence Journal-World.19 - David Cramer20+- Adrian Mönnich (ThiefMaster)21 22 Patches and suggestions:23 24 - Ronny Pfannschmidt10 unmodified linesmodified:CHANGES+6 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+- Added `changed(*values)` to loop contexts, providing an easy way of checking17+ whether a value has changed since the last iteration (or rather since the18+ last call of the method)19 20 Version 2.9.621 -------------22 (bugfix release, released on April 3rd 2017)504 unmodified lines