Skip to content
Myr

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

8 files+134 added−13 removed

modified:docs/templates.rst+33 added
610 unmodified lines
611+-----------------------+---------------------------------------------------+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+-----------------------+---------------------------------------------------+624625Within a for-loop, it's possible to cycle among a list of strings/variables626each time through the loop by using the special `loop.cycle` helper::627
60 unmodified lines
688a bug where in some circumstances it appeared that assignments would work.689This is not supported. See :ref:`assignments` for more information about690how to deal with this.691692If all you want to do is check whether some value has changed since the693last iteration or will change in the next iteration, you can use `previtem`694and `nextitem`::695696 {% 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 %}705706If you only care whether the value changed at all, using `changed` is even707easier::708709 {% for entry in entries %}710 {% if loop.changed(entry.category) %}711 <h2>{{ entry.category }}</h2>712 {% endif %}713 <p>{{ entry.message }}</p>714 {% endfor %}715716.. _if:717718If719~~
880 unmodified lines
modified:jinja2/asyncsupport.py+8 added-6 removed
187 unmodified lines
188189190class AsyncLoopContext(LoopContextBase):191192 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 lines
220 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, ctx231232232async def make_async_loop_context(iterable, recurse=None, depth0=0):233async 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 lines
251 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 lines
1111 if node.test:1112 self.write(')')11131114 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 ':')11181119 self.indent()1120 self.enter_frame(loop_frame)1121
576 unmodified lines
modified:jinja2/runtime.py+30 added-5 removed
34 unmodified lines
3536#: the identity function. Useful for certain things in the environment37identity = lambda x: x3839_first_iteration = object()40_last_iteration = object()414243def markup_join(seq):
305 unmodified lines
349350class LoopContextBase(object):351 """A loop context for dynamic iteration."""352353 _before = _first_iteration354 _current = _first_iteration355 _after = _last_iteration356 _length = None357355 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 = missing364365 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)]370371 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 False377378 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)384385 @property386 def previtem(self):387 if self._before is _first_iteration:388 return self._undefined('there is no previous item')389 return self._before390391 @property392 def nextitem(self):393 if self._after is _last_iteration:394 return self._undefined('there is no next item')395 return self._after396397 def __len__(self):398 return self.length399400 @internalcode
17 unmodified lines
418419420class LoopContext(LoopContextBase):421398 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)425426 # try to get the length of the iterable early. This must be done427 # here because there are some broken iterators around where there
43 unmodified lines
471 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, ctx479480481class Macro(object):482 """Wraps a macro function."""
330 unmodified lines
modified:tests/test_async.py+27 added
302 unmodified lines
303 for item in seq %}{{ loop.cycle(*through) }}{% endfor %}''')304 output = tmpl.render(seq=list(range(4)), through=('<1>', '<2>'))305 assert output == '<1><2>' * 4306307 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|'314315 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,'321322 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 output
19 unmodified lines
345 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]>]'348349 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]>]'360361 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 lines
modified:tests/test_core_tags.py+27 added
66 unmodified lines
67 for item in seq %}{{ loop.cycle(*through) }}{% endfor %}''')68 output = tmpl.render(seq=list(range(4)), through=('<1>', '<2>'))69 assert output == '<1><2>' * 47071 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|'7879 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,'8586 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 output
19 unmodified lines
109 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]>]'112113 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]>]'124125 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 lines
modified:AUTHORS+1 added
15 unmodified lines
16- Mickaël Guérin <kael@crocobox.org>17- Cameron Knight18- Lawrence Journal-World.19- David Cramer20- Adrian Mönnich (ThiefMaster)2122Patches and suggestions:2324- Ronny Pfannschmidt
10 unmodified lines
modified:CHANGES+6 added
8 unmodified lines
9 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)1920Version 2.9.621-------------22(bugfix release, released on April 3rd 2017)
504 unmodified lines