From 898975dd5d02fcbc13dbe19ff65a50b43820df1a Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Thu, 6 Oct 2011 10:09:31 -0400 Subject: [PATCH] Added a dict iteration example. This fixes #64 --- docs/templates.rst | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/docs/templates.rst b/docs/templates.rst index 48429a5..3032e3a 100644 --- a/docs/templates.rst +++ b/docs/templates.rst @@ -497,7 +497,21 @@ provided in a variable called `users`:: {% endfor %} -Inside of a for loop block you can access some special variables: +As variables in templates retain their object properties, it is possible to +iterate over containers like `dict`:: + +
+ {% for key, value in my_dict.iteritems() %} +
{{ key|e }}
+
{{ value|e }}
+ {% endfor %} +
+ +Note however that dictionaries usually are unordered so you might want to +either pass it as a sorted list to the template or use the `dictsort` +filter. + +Inside of a for-loop block you can access some special variables: +-----------------------+---------------------------------------------------+ | Variable | Description | @@ -529,7 +543,7 @@ each time through the loop by using the special `loop.cycle` helper::
  • {{ row }}
  • {% endfor %} -With Jinja 2.1 an extra `cycle` helper exists that allows loop-unbound +Since Jinja 2.1 an extra `cycle` helper exists that allows loop-unbound cycling. For more information have a look at the :ref:`builtin-globals`. .. _loop-filtering: -- 2.26.2