Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions doc/tags/for.rst
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,40 @@ Variable Description
``loop.last`` variables are only available for PHP arrays, or objects that
implement the ``Countable`` interface.

The ``loop.parent`` variable gives access to the context enclosing the ``for``
loop. It is not limited to nested loops: it exposes the whole context as it was
before the loop started, which covers two common needs.

When loops are nested, the parent context holds the outer ``loop`` variable, so
the inner loop can reach the outer iteration state:

.. code-block:: twig

{% for topic, messages in topics %}
* {{ loop.index }} : {{ topic }}
{% for message in messages %}
- {{ loop.parent.loop.index }}.{{ loop.index }}: {{ message }}
{% endfor %}
{% endfor %}

Here ``loop.parent.loop.index`` is the index of the current ``topic`` from the
outer ``for`` loop.

``loop.parent`` also lets you reach a variable that the loop variable shadows:
when both share the same name, the outer value is still available through the
parent context:

.. code-block:: twig

{% set user = 'Fabien' %}
{% for user in ['Homer', 'Bart'] %}
{{ loop.index }}. {{ user }} (outer user: {{ loop.parent.user }})
{% endfor %}

This outputs ``1. Homer (outer user: Fabien)`` then ``2. Bart (outer user: Fabien)``.

See also :doc:`the recipe on accessing the parent context in nested loops <recipes>`.

The ``else`` Clause
-------------------

Expand Down