Building data-driven web apps with Flask and SQLAlchemy Transcripts
Chapter: Jinja2 templates
Lecture: Concept: @response a better render_template
0:00 Let's review the concepts around render template
0:02 and create a decorator to make that a little bit nicer.
0:05 So, personally I find it much nicer to save.
0:09 This page has this one and only view
0:10 this one and only template
0:12 and we're going to past potentially different data to it.
0:15 Or we're going to redirect it to a different view.
0:17 That actually has a different template.
0:19 We'll talk more about this when we get to the form
0:22 and user input and the thing called the get
0:25 post redirect pattern and so on.
0:27 But this pattern here, having a decorator
0:30 of the template file actually makes that much cleaner
0:33 and easier.
0:34 So, here we can just create this response decorator
0:37 and this isn't officially a Flask thing.
0:39 This is just something I wrote
0:40 that I feel like is a lot nicer.
0:42 So, let's reset the template file and the mime type, uphere.
0:46 And then, all you have to do is past the data in the form
0:49 of a dictionary or list. Something to that affect.
0:53 So, this is super nice.
0:54 The code to make it happen, not so much.
0:57 Not so nice, but here you'll have this code inside
1:01 the demo app.
1:02 So, no worry you don't have to like type this in
1:05 or anything. But it's one of these, sort of decorators, that takes
1:08 an argument.
1:09 So, it's like a double decorator and you got a function
1:12 with an inner function, with an inner function.
1:14 And then it just goes through and it looks at the data
1:17 that was passed to it.
1:18 When it runs the data actually gets back, when it calls
1:20 that inner function, it says if it's a response
1:23 we're just going to let whatever you create flash response.
1:25 We can't mess with that we're going to let it go.
1:28 But, if for some reason you created, you want to say
1:31 a useless template file, you have to pass a dictionary.
1:33 And it's going to pass that data along just like
1:36 it would before and also it allows you to set
1:38 the mime type on the generated response error.
1:41 Which is also helpful.
1:42 Sometimes, you want to return like text or csv
1:45 or something like that.
1:46 You can also use a template for that.
1:48 Okay, so here it is.
1:49 This I think, for me this is an improvement on the render
1:52 template style that Flask uses.
1:54 If you don't like, you know it's completely optional
1:57 but I prefer to see code like this.
1:58 Then a whole bunch of render template all over the place.