Flask: Using For Loops Inside HTML

Flask: Using For Loops Inside HTML

In our previous video, we saw how to get data passed from a run.py file on the backend through to our HTML templates on the frontend. In this video then, we’re going to have a look at how we can reduce repetition even more. So just to show as an example, I’m going to go back to my run.py file, and I’m going to add in an another additional argument to our return here. I’m going to call that list_of_numbers. And I’m going to set that equal to [1, 2, 3]. So I’m creating a standard Python list. Now as we know, I can display a variable in my HTML by using the double curly bracket notation and then putting my expression in there. Let’s do that again. So {{list_of_numbers}} So I’m going to save that and go back to my page. I’m still on the Careers page here, let me just switch to About. Then we can see that our list is displayed in the square brackets. But what I want to do now is use a for loop in my HTML to iterate over that list. And to do that, we use the {% notation because, remember, this is for statements, not for expressions. This is logic control here. And we’re going to put in a standard Python for loop for number in list_of_numbers. We then need to supply an {%end for%} so that the templating language knows where the for loop stops. Inside the for loop then, I’m going to put some

tags and then inject number inside the two curly braces to display that to screen. Now this is a for loop. What it’s going to do is iterate around through the list of numbers and then display that number in

tags on
the screen. And the word number here is not a reserved word. That’s just a variable name that we’ve created. We could have called it anything we wanted. So now when I refresh the page, I have 1, 2, and 3. And if I inspect the HTML here, then you can see that I have three paragraphs: 1, 2, and 3. So our for loop has created three sets of

tags and injected the value from our list_of_number into each one. That’s quite a trivial example. But what we’re going to do in our next few videos is bring all of these things that we’ve learned together by iterating over data in a file and displaying it to screen.

Leave a Reply

Your email address will not be published. Required fields are marked *