Building Data-Driven Web Apps with Flask and SQLAlchemy Transcripts
Chapter: Jinja2 templates
Lecture: Concept: @response a better render_template

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Let's review the concepts around render template and create a decorator to make that a little bit nicer. So, personally I find it much nicer to save.
0:10 This page has this one and only view this one and only template and we're going to past potentially different data to it.
0:16 Or we're going to redirect it to a different view. That actually has a different template. We'll talk more about this when we get to the form
0:23 and user input and the thing called the get post redirect pattern and so on. But this pattern here, having a decorator
0:31 of the template file actually makes that much cleaner and easier. So, here we can just create this response decorator
0:38 and this isn't officially a Flask thing. This is just something I wrote that I feel like is a lot nicer.
0:43 So, let's reset the template file and the mime type, uphere. And then, all you have to do is past the data in the form
0:50 of a dictionary or list. Something to that affect. So, this is super nice. The code to make it happen, not so much.
0:58 Not so nice, but here you'll have this code inside the demo app. So, no worry you don't have to like type this in
1:06 or anything. But it's one of these, sort of decorators, that takes an argument. So, it's like a double decorator and you got a function
1:13 with an inner function, with an inner function. And then it just goes through and it looks at the data that was passed to it.
1:19 When it runs the data actually gets back, when it calls that inner function, it says if it's a response
1:24 we're just going to let whatever you create flash response. We can't mess with that we're going to let it go.
1:29 But, if for some reason you created, you want to say a useless template file, you have to pass a dictionary.
1:34 And it's going to pass that data along just like it would before and also it allows you to set the mime type on the generated response error.
1:42 Which is also helpful. Sometimes, you want to return like text or csv or something like that. You can also use a template for that.
1:49 Okay, so here it is. This I think, for me this is an improvement on the render template style that Flask uses.
1:55 If you don't like, you know it's completely optional but I prefer to see code like this. Then a whole bunch of render template all over the place.


Talk Python's Mastodon Michael Kennedy's Mastodon