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.
0:03
And templates are like HTML
0:04
with a little bit of Python sprinkled in.
0:07
So here's what you'd call a Jinja2 template
0:10
and the idea is given a list of packages
0:13
maybe the popular ones, who knows
0:14
we want to loop over and create a bunch of little HTML divs
0:17
and each one of those divs is going to
0:19
contain a hyperlink, a summary
0:22
and things like that, if there is a summary.
0:25
So let's unpack some of these little features here.
0:28
Here we have conditionals
0:30
and loops and so on in these {% things.
0:34
So we say {% for p in packages %}
0:38
Remember packages has probably passed over
0:40
as part of the model, something iterable here
0:42
with an ID and a summary.
0:44
We define a little looping variable p
0:46
and all the HTML in there gets repeated.
0:48
So if there were three packages
0:49
that div would appear three times in the final HTML.
0:54
Notice the bottom here, we have this {% end for %}
0:56
So whenever you open one of these
0:57
like for p in packages, we have to close it.
0:59
We also have if summary, end if.
1:01
Personally, it drives me crazy that this is how its done
1:05
but this is how it's done.
1:07
If we want to take a value and convert it to text
1:10
we would just put it in {{ }}.
1:12
So here, the id is actually a string
1:15
which is the package name, like SQLAlchemy
1:17
or something like that.
1:19
SQLAlchemy, MongoEngine, Flask, whatever.
1:21
I want to show that as the link text.
1:24
I basically want the text of the name of the project
1:27
to be shown, and I also want to link to it
1:29
like /project, /flask. So we can do {{ }}
1:33
both inside the attributes for the URL
1:35
and inside of the tag to just show the text.
1:39
We also can have conditionals.
1:41
Here we can have if there is a summary
1:44
we're going to show a span.
1:45
But if for some reason this particular project
1:47
doesn't have a summary, just omit
1:49
that whole block of HTML altogether.
1:54
When you're finally rendered
1:55
it looks potentially something like this
1:57
depending on the data we pass in.
1:58
So here's the request, that's the name p.id
2:01
as well as the extended URL's going to be
2:03
/project/request.
2:06
And that summary is HTTP4, and the next one is Boto3
2:09
AWS API is the summary, and so on.
2:12
Now this is entirely un-styled
2:14
but we're going to be doing all sorts
2:15
of cool stuff to make this look much better as we go.
2:19
We won't spend a lot of time working on templates
2:21
but I think you'll pick them up pretty quickly.
2:23
They're basically HTML with a little bit
2:25
of Python sprinkled on top of them.