Building Data-Driven Web Apps with Flask and SQLAlchemy Transcripts
Chapter: Jinja2 templates
Lecture: Jinja2 template example

Login or purchase this course to watch this video and the rest of the course contents.
0:00 So let's take this data and put it into a Jinja template and make dynamic HTML out of it. So, here's one little code snippet, not all the HTML.
0:11 Obviously, there's not the HTML on the head and the body and like, that kind of stuff but just to focus on the essence of it, if you will.
0:17 So, we have two situations. One where we're given that data but there's no categories; it's like an empty list or something like that.
0:24 You know, we did a database query and like "Hey, it's not set up," or whatever. So, we want to just show on this page there's no categories.
0:31 But if there are, we want to loop over them and add a div with two hyperlinks one for the image and one for the name.
0:38 So, a couple of things should jump out at you right away. Any time we have some kind of conditional
0:44 or command or loop or something like that involving Python we say, {% we insert some Python and we say, %} to close it off. So, if not categories
0:56 so we want to show this div at the top that says, no categories, only if there's no categories. And we don't just have the opening block
1:04 we also have an ending block. So, if you say, if something, you have to say, end if. Notice at the bottom we have for something, and for.
1:12 So you got to open and close these both with little percent block indicators at the front and the end of the statement
1:18 but also at the end of the block. So, we have our, if statement, on the one hand we could also do an else if we really wanted but that's okay.
1:26 We're just going to go with two if's effectively the same. Then we're going to do a for loop. So, we're just going to have {% for c in categories %}
1:32 that's standard Python. And this is going to define a local variable c. And in here we have some HTML blocks that gets repeated for each c
1:40 for each little category in for thing there. And we're going to have two hyperlinks and we want to have the hyperlinks contain the name of category.
1:48 So, like /category/comfort /category/downhill/, or whatever. Then we're also going to have the image. So, we just say {{
1:58 or sometimes those are called mustaches or handlebars but call it what you like. {{ and then we say c and we can apply further Python.
2:07 So it's c.name, pulls out that value of the dictionary and then .lower, lowercases that string just to make sure
2:13 that the URL is kind of normalized there. Then c.image will get the URL and we want to show the name also in the bottom one without being lowercase
2:21 so we just say c.name. Pretty straightforward, right? This is, honestly, most of what you need to know to work with Jinja outside of additional
2:29 just the standard HTML stuff that you're going to be doing.


Talk Python's Mastodon Michael Kennedy's Mastodon