Building Data-Driven Web Apps with Flask and SQLAlchemy Transcripts
Chapter: Introducing the Flask framework
Lecture: Building block: Dynamic HTML Templates
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
Final building block is templates. And templates are like HTML with a little bit of Python sprinkled in. So here's what you'd call a Jinja2 template
0:11
and the idea is given a list of packages maybe the popular ones, who knows we want to loop over and create a bunch of little HTML divs
0:18
and each one of those divs is going to contain a hyperlink, a summary and things like that, if there is a summary.
0:26
So let's unpack some of these little features here. Here we have conditionals and loops and so on in these {% things. So we say {% for p in packages %}
0:39
Remember packages has probably passed over as part of the model, something iterable here with an ID and a summary.
0:45
We define a little looping variable p and all the HTML in there gets repeated. So if there were three packages
0:50
that div would appear three times in the final HTML. Notice the bottom here, we have this {% end for %} So whenever you open one of these
0:58
like for p in packages, we have to close it. We also have if summary, end if. Personally, it drives me crazy that this is how its done
1:06
but this is how it's done. If we want to take a value and convert it to text we would just put it in {{ }}. So here, the id is actually a string
1:16
which is the package name, like SQLAlchemy or something like that. SQLAlchemy, MongoEngine, Flask, whatever. I want to show that as the link text.
1:25
I basically want the text of the name of the project to be shown, and I also want to link to it like /project, /flask. So we can do {{ }}
1:34
both inside the attributes for the URL and inside of the tag to just show the text. We also can have conditionals.
1:42
Here we can have if there is a summary we're going to show a span. But if for some reason this particular project doesn't have a summary, just omit
1:50
that whole block of HTML altogether. When you're finally rendered it looks potentially something like this depending on the data we pass in.
1:59
So here's the request, that's the name p.id as well as the extended URL's going to be /project/request.
2:07
And that summary is HTTP4, and the next one is Boto3 AWS API is the summary, and so on. Now this is entirely un-styled
2:15
but we're going to be doing all sorts of cool stuff to make this look much better as we go. We won't spend a lot of time working on templates
2:22
but I think you'll pick them up pretty quickly. They're basically HTML with a little bit of Python sprinkled on top of them.