From 7cbc43a10f5249ee7cd8b76e8788dbc27550b3bc Mon Sep 17 00:00:00 2001 From: fabien Date: Wed, 6 Jan 2010 15:20:16 +0000 Subject: [PATCH] added an example of a nested loop to demonstrate the usage of loop.parent git-svn-id: http://svn.twig-project.org/trunk@213 93ef8e89-cb99-4229-a87c-7fa0fa45744b --- doc/02-Twig-for-Template-Designers.markdown | 33 +++++++++++++++++++++++++++ 1 files changed, 33 insertions(+), 0 deletions(-) diff --git a/doc/02-Twig-for-Template-Designers.markdown b/doc/02-Twig-for-Template-Designers.markdown index 7da2faf..906bdaf 100644 --- a/doc/02-Twig-for-Template-Designers.markdown +++ b/doc/02-Twig-for-Template-Designers.markdown @@ -445,6 +445,7 @@ Inside of a `for` loop block you can access some special variables: | `loop.first` | True if first iteration | `loop.last` | True if last iteration | `loop.length` | The number of items in the sequence +| `loop.parent` | The parent context >**NOTE** >Unlike in PHP it's not possible to `break` or `continue` in a loop. @@ -486,6 +487,38 @@ You can also access both keys and values: >On Twig before 0.9.3, you need to use the `items` filter to access both the >keys and values (`{% for key, value in users|items %}`). +When using nested loops, the parent context is accessible via the +`loop.parent` variable. For instance, if you have the following template data: + + $data = array( + 'topics' => array( + 'topic1' => array('Message 1 of topic 1', 'Message 2 of topic 1'), + 'topic2' => array('Message 1 of topic 2', 'Message 2 of topic 2'), + ), + ); + +And the following template to display all messages in all topics: + + [twig] + {% for topic, messages in topics %} + * {{ loop.index }}: {{ topic }} + {% for message in messages %} + - {{ loop.parent.loop.index }}.{{ loop.index }}: {{ message }} + {% endfor %} + {% endfor %} + +The output will be similar to: + + * 1: topic1 + - 1.1: The message 1 of topic 1 + - 1.2: The message 2 of topic 1 + * 2: topic2 + - 2.1: The message 1 of topic 2 + - 2.2: The message 2 of topic 2 + +In the inner loop, we use the `loop.parent` to access the outer context. So, +the index of the `topics` for loop is accessible via `loop.parent.loop.index`. + ### If The `if` statement in Twig is comparable with the if statements of PHP. In the -- 1.7.2.5