From 7234d51ec86f6661956d1e642ede1a18f2902ec7 Mon Sep 17 00:00:00 2001 From: Marilena RUFFELAERE <143809776+marilenaRM@users.noreply.github.com> Date: Fri, 17 Jul 2026 15:42:51 +0200 Subject: [PATCH] Update for.rst Add context and explanation about loop.parent --- doc/tags/for.rst | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/doc/tags/for.rst b/doc/tags/for.rst index 1e78db63c..4447bbdf7 100644 --- a/doc/tags/for.rst +++ b/doc/tags/for.rst @@ -80,6 +80,25 @@ Variable Description ``loop.last`` variables are only available for PHP arrays, or objects that implement the ``Countable`` interface. +When loops are nested, you can access the parent loop context via the +``parent`` key of the ``loop`` variable: + +.. code-block:: twig + + {% for topic, messages in topics %} + * {{ loop.index }} : {{ topic }} + {% for message in messages %} + - {{ loop.parent.loop.index }}.{{ loop.index }}: {{ message }} + {% endfor %} + {% endfor %} + +In the inner loop, ``loop.parent`` gives access to the context of the +enclosing loop. So, the index of the current topic (defined in the outer +``for`` loop) is available in the inner loop via +``loop.parent.loop.index``. + +See also :doc:`the recipe on accessing the parent context in nested loops `. + The ``else`` Clause -------------------