Repetitive tasks are standard in most computer applications and template rendering is no different. Creating lists, tables or a group of images are all repetitive tasks that can be solved using for loops.
Using the same statement delimiter block as if statements {% %}
, for loops step through a range of numbers, lists and dictionaries.
The following code will create an ordered list where each line will output the index of the sequence:
<ol> {% for x in range(3) %} <li>{{ x }}</li> {% endfor%} </ol> OUTPUT 1. 0 2. 1 3. 2
The syntax is similar to a Python for loop where we define a loop variable x
to step through a series of numbers using range(3)
. The local loop variable can be used inside our loop with the expression delimiter {{x}}
.
Similar to the if statements we need to close the loop with an {%endfor%}
block.
The following are a few more applications of a for loop.
Iterate through a list variable:
{% for element in template_list %}
Iterate through a string:
{% for char_in_string in “Hello!” %}
Iterate through the keys of a dictionary variable:
{% for key in template_dict %}
Iterate through keys AND values of a dictionary with items()
:
{% for key, value in template_dict.items() %}
Using the filter dictsort
in a loop outputs the key/value pairs just like items()
Instructions
Loops can help create lists based on the length of the data we have to work with.
In recipe.html the ingredients section now has one <li>
element. Apply a for loop to create an HTML list based on the Python list template_ingredients
.
Note the variable name ingredient
to be used as the loop variable.
In the instructions section, remember that we are using the dictsort
filter on template_instructions
. When used in a for loop dictsort
will give you access to both the key and value of the dictionary.
Using the key
and instruction
variables create a simple string inside the <p>
tag. The output should resemble something like this:
Step 1: Put the bread in the toaster
Now let’s move to index.html and support the expansion of our recipe list. The dictionary of ids and recipes names is now accessible in the template through the variable template_recipes
.
Create a for
loop around the hyperlink and iterate through template_recipes.items()
. Name the key and value loop variables id
and name
respectively.
Use the id
and name
variables to complete the hyperlink URL and the display string.
Once the code is run you can now add recipes to the application data and automatically get a link on the index page that connects to a custom recipe page.