# Python Flask Tutorial: Full-Featured Web App Part 2 - Templates

## Метаданные

- **Канал:** Corey Schafer
- **YouTube:** https://www.youtube.com/watch?v=QnDWIZuWYW0
- **Дата:** 04.05.2018
- **Длительность:** 31:41
- **Просмотры:** 937,909

## Описание

In this Python Flask Tutorial, we will be learning how to use templates. Templates allow us to reuse sections of code over multiple routes and are great for serving up dynamic HTML pages. Let's get started...

The code for this series can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog

The code snippets used in this video can be found here:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog/snippets


✅ Support My Channel Through Patreon:
https://www.patreon.com/coreyms

✅ Become a Channel Member:
https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join

✅ One-Time Contribution Through PayPal:
https://goo.gl/649HFY

✅ Cryptocurrency Donations:
Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3
Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33
Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot

✅ Corey's Public Amazon Wishlist
http://a.co/inIyro1

✅ Equipment I Use and Books I Recommend:
https://www.amazon.com/shop/coreyschafer

▶️ You Can Find Me On:
My Website - http://coreyms.com/
My Second Channel - https://www.youtube.com/c/coreymschafer
Facebook - https://www.facebook.com/CoreyMSchafer
Twitter - https://twitter.com/CoreyMSchafer
Instagram - https://www.instagram.com/coreymschafer/

#Python #Flask

## Содержание

### [0:00](https://www.youtube.com/watch?v=QnDWIZuWYW0) Intro

hey there how's it going everybody in this flats tutorial we'll be learning how to use templates to return more complex HTML code than we did in our last video and also how to pass variables to our web page so let's go ahead and get started so I'm starting with the same script that we left off with in our last video with these two routes for our home page and our about page so we can see in our to route functions that we're returning these two HTML headings but most HTML files have a lot more HTML code than this it contains a next tire structure with a head tag body tag and all of that now there's nothing stopping us from returning all of that HTML here we could for example instead of just returning this one heading tag I could put in 3 quotes for a multi-line string and I could just return all of this here and say you know doctype HTML then open up the HTML tag and just kind of keep going there but you can imagine that with a lot of pages and routes that this would get really ugly really fast and that we'd create a ton of repeated HTML like this for every single route so the best way to do this would be to instead use templates so to use templates we first need to create a templates directory within our folder within our project I mean and I'll do that here within sublime text so I'm just going to right click on my project and say new folder and I'm going to call this templates and that's all lowercase and now within our templates directory

### [1:22](https://www.youtube.com/watch?v=QnDWIZuWYW0&t=82s) Creating templates

I'm going to create templates for both of our routes that we currently have so I'm going to create one for our home route and one for our about route so I'm gonna right click on our templates page here and say new file and I will call one of these home HTML and I will create another new file and call this one about dot HTML and let's do our home route first so I'll put all of the HTML that we'd like to have within our home page within this template here so in sublime text if I just type HTML and then press tab then we can see that it fills out you know a minimal HTML page structure for us now if your editor doesn't create a structure like this then you can find these pages in my github code and I'll leave a link to that in the description section below if you'd like to copy and paste it from there so now that we have a basic HTML structure let's the heading tag that we had in our Python script into this home template so I'm going to go back to our application and just grab one of these heading tags so this is our about page tag here and I'm gonna paste this into our home template and just so I'll go to the body here and paste that in and change about to home so that we have home page and now that we have this home template ready let's actually use this template when we navigate to our home page so if we go back to our application then instead of returning just plain HTML here instead we can render the template so first we're going to have to import the render template function from flask so up here in our import statement I'm just going to put a comma and add in the render template function that we want to import and now for our return statement here we can say return render template and now the template that we want to render and that template for our home route is home HTML so now let's save this and run it from our command line to make sure that it works so I will pull back up my terminal here now if you don't have your terminal open then you have to have it open and navigate to your project directory like we did in the last video and if you remember in that video we can run our application just by saying Python flask blog PI we can see that it's running on our localhost and debug mode so I'll pull up our web browser here and reload that page and we can see that this looks about the same as it did before but if I right click and go to view page source then we can see that instead of just that h1 tag that now we have an entire HTML structure here so it is pulling that structure from at that template ok so now let's do the same thing for our about page so I'm gonna pull back up our application here and I'm gonna go to our home template first and copy this structure and paste it into our about HTML and I'll change this to be the about page instead of homepage and then within our application we can't forget that we actually have to actually render that template now so I will copy this from our home ramp and replace that heading tag and the template that we want to render there is about dot HTML so I'll save that back up our site and go to the ford slash about page we can see that it looks similar to what it did in the first video but if we view our page source then now we have that entire HTML structure that it's pulling from that template so that worked so I'll pull back up my application here so if you

### [4:45](https://www.youtube.com/watch?v=QnDWIZuWYW0&t=285s) Adding dummy data

were just using flash to basically serve up static HTML pages then that's basically what we've created here all you have to do is add in more detailed HTML and CSS and you'd be good to go but pretty much every web application these days doesn't just contain static information I usually have you know posts and updates and all kinds of different information that is being added to the site on a regular basis so for example if you remember the application that I showed in the first video that I said would be our final application at the end of this series it had a lot of different posts by different authors and those could have been blog post or pictures or whatever it is that you're making with your application so let's say that we had some posts like this that we wanted to display in our template so how would we do that so let's add some dummy data so that we can see how this is actually passed into our template so I'm just going to add some dummy data to the top of the file here and I'm just going to call this post and I'm going to set this equal to a list and this is going to be a list of dictionaries and each dictionary is going to represent a single blog post so for example I will have an author here and I'll just fill out some sample information so I'll have an author of Corey Schaeffer a title and I'll just set this to a blog post one and then I will also have some content and the content we will say is first content or how about first post content okay and then lastly let's also do a date posted so for a date posted I'll just pass in a string here so we'll say April 20th 2018 so now let's add in a nother dictionary here with some different data to represent another dummy blog post so we'll change some of this information up so we'll say that this author is Jane Doe for the title will say blog post to second post content and will say that this is April 21st 2018 okay so for now let's pretend that we made a database call and got back this list of posts and that's what this post variable is now we can pass these posts into our template just by passing an argument with our data so if I came down here to our home template then within our render template function I could simply say posts is equal to posts so now whatever variable name we use as the argument name here that we pass in we will have access to that variable in our template and it will be equal to this post data so now let's switch over to our home template and see how we would look through this post data so the templating engine that flask uses is called Jinja - and it allows us to write code here within our templates so to write a for loop we can open up a code block and a code block is represented by these curly braces and then two parentheses here and within these we can say for post in post and we also have to tell the templating engine when the for loop ends and we just do that with another code block so that's curly braces and parentheses and we can just say in for so now within this for loop we can print out our post information one post at a time so if we come in here let's say that we wanted to print out the post title in an h1 tag so we can just say h1 and now that we want to print out an actual variable this isn't going to be the same as the code block with the curly braces and parentheses this is just going to be two curly braces because now a variable that we're printing out so we'll say that we want to print out the post dot title and we can use this dot access here within the template so that dot access does work so now let's print out a paragraph tag and let's print out the author and the date that it was posted as well so I'll say bye and then we want to put the post author here so we'll put in our double curly braces post dot author and within the same paragraph I'll print out the date that it was posted on so I'll say on and then we want to say post dot and I believe I called this okay this was date posted so we want to use this date posted attribute there and lastly let's print out the actual content of the post so just like we were doing before the two curly braces and post dot content so real quick let's just look over this again so we're opening up a code block here and that code block says for posts and we got this post value here this variable we got that by passing in this argument into our template and this argument is equal to this post dummy data here at the top so this post variable within our template is going to be equal to this data so that is where this comes from here so we're looping over those posts and for each one we're going to print out this information of the post so if we save that now let's see if this worked so our web server is still running so I'm going to go back to our home page and see if we get that data so we can see that it looped over our dummy data and displayed the information that we specified within the HTML and if I view the page source to actually view the HTML that it gave to us now this is a little small here but we can see that it has both of these sections that were created here within the for loop okay so now let me open up our home template again here so I'll pull up sublime text so we saw how to do a for loop but we

### [10:30](https://www.youtube.com/watch?v=QnDWIZuWYW0&t=630s) Ifelse conditionals

can also do if else conditionals as well so let's say that we wanted to be able to pass a title to our web pages but if we didn't pass a title then we just want to use a default of flask blog or something like that so we could come up here to our title and I will just type in the default title that we would want for our page here and we'll call that flask blog but now let's add in an if-else conditional here to where if we actually passed in a title into this template then it would print out flask blog - title or something like that so to do an if statement we our code block here with the curly braces and parentheses and instead of a for loop will say if title and then I will copy this here and paste that here and now we can do an else end this I'll paste that in again just like we ended the for loop by saying end if so this title that we currently have is what we want as our default title so I'm going to put that in our else block because we want that to be the default if no title is provided and if there is a title provided then we want it to be flashed up blog - and then print out that title that we pass in and mostly what this looks like in just a second and let's also add this title section to our about template as well so I'm going to copy this entire if-else conditional and paste that in here to the head section so now if we go back to our application code let's not pass in a title for our home template because we just want that to be the default for our application but for our about page let's pass in a title of about so I will put in a comma there and just say title is equal to about so for our home page template where we didn't pass in a title then it should come in here and say if title and see that it doesn't have one so it'll come down and just use this flash blog as the title in our about template it'll see that we do have a title that we passed in and it will use this title here instead so now I'm gonna pull this back up in our browser and reload these pages so I'll reload this and we can see here in our tab that the title of this page is now called flask blog and if we view the page source we can see that well that too and I know that this text is a little small here but if we go to our about page so ford slash about now we can see that the title of this page and our tab is flash blog - about so it is setting those values correctly using our conditional okay so we're almost finished up with this tutorial but there is one thing about our templates that isn't a very good design so if you notice our home page template and our about template have a lot of similar repeated code so if I pull those up and compare those we can see that a lot of

### [13:32](https://www.youtube.com/watch?v=QnDWIZuWYW0&t=812s) Template inheritance

this is similar and there's just this one section here down in the body that is different and that's never a good thing in programming because it means that if we want to update one of those sections then we need to update it in every single location so for example if we wanted to change our default title for our website then we would have to make that change in both the home and the about template so it's almost always better to have everything that is repeated in a single place so that there is only one place to make changes and our home template and about template only contain the information that is unique to those pages so to accomplish this we can use something called template inheritance so let's see what this looks like so I'm going to create a new template in our templates directory and I'm gonna call this layout dot HTML so within our templates I'm going to create a new file here and I'm gonna call this layout dot HTML and hit enter there to create that file and within layout that HTML we want to pick out all of the repeated sections between our home and our about templates so if we compare these back and forth like we

### [14:37](https://www.youtube.com/watch?v=QnDWIZuWYW0&t=877s) Block content

said before the only thing that is different is this body section so I'm going to copy the code from one of our templates here I'll use the about template and paste this into our layout dot HTML template and then I'll just delete the part that is unique here to the about page I'll just delete everything within the body tag there so now we only have the HTML that is shared between both of our routes so now I'm going to create a block and a block is a section that the child templates can override so we'll see this in action in just a second so I'll create a block within our body tag and I'll just call this block content so to do this we can use the code blocks that we've seen before and instead we're going to use this block keyword so I'll say block content and that's what we're calling it this block and then do another code block right after this and then we want to end that block so I'll say end block so now within our home and about templates we'll inherit this layout template and get all of this information but then we'll just override the content section with the stuff that is unique to each page so I'll switch over here to the home template and in this template we want to use that layout template as the parent so we can get rid of all the information that is in that layout template so that is everything that is outside of the body so I will remove all of this here and basically we're just keeping the for loop that is unique to this home page so now at the top of this template we can use that layout template by opening up a code block here and using the extends keyword and we want to extend that layout dot HTML template and now we want this for loop content here to override the content block of that layout template so to do that we can wrap it in a Content block by saying and I'm going to indent this here so we can just open up a Content block here by saying a block content and then down here at the bottom we will end that so I will do another content block and say end block now the way that we have it here would work and this is how I see most people doing it but Jinja to the templating engine that we're using actually allows you to put the name of the block after the end block as well and I like doing that because if you have multiple blocks then it can be easy to lose track of what blocks you're closing so I like to be explicit so after M block here I'm gonna say in block content so content there isn't needed but like I said I like to put it just to be explicit that it's actually closing off this block here okay so now let's do the same thing with our about template and I'll just copy everything that we have here and paste it into our about template here at the top but instead of our content being just this for loop here it's just going to be this h1 heading so I'll grab this h1 heading and paste that into our content block and now we can get rid of everything that was here before okay so I know that may have been a lot to take in so we'll go back over that again once we make sure that this is all still working so after we save this then we should be able to reload it in our browser and still have the same pages that we had before so let's check this out really fast so let's make sure that our web server is still running now we'll pull back up Chrome here and if we go to our about page we can see that works and if we go to our home page we can see that still works as well and if we actually check the source code of these pages then we can see that it still has the entire HTML structure there as well so all of that is still working so these pages look the same as they did before but now we're using that template inheritance so that we're not repeating code so let me show you why this is so powerful so let's say that we wanted to now update our entire website to use bootstrap now if you don't know what bootstrap is basically and exit it's an extremely popular library that makes it easy to add some nice styles to your website and i'll be using bootstrap in this series since it will allow us to add nice Styles easily without taking away any of the focus from flask so to add bootstrap to our website I'm going to open up the starter template from the bootstrap documentation to see how they say to do this and already have this open up here so this is a basic starter template that they give here and we can see that we need to add some tags and a link to some CSS here in the head of the website and also down here at the bottom right before the closing body tag we need to add some JavaScript files as well now the CSS and JavaScript it's using are all served from a CDN which is a content delivery network so there's nothing we actually need to download so we should just be able to drop this in to our site and we'll be good to go now there is actually a flask extension for bootstrap called flask bootstrap and I won't be using that in this video because I feel like it's something additional to learn and if you're already familiar with bootstrap classes then there's really no reason that you can't just use it directly and also I feel like it just gives you a bit more control with the design just to do it manually but if anyone is interested then I could show how to use the flask bootstrap extension and a later video now if we weren't using template inheritance then we'd have to make these changes to every template in our application and not only would that be easy to screw up but it would be almost impossible to maintain once the number of pages on our website you know grew to a certain level but now we just need to make these changes to that single layout template that our other templates inherit from so to do this I'll first copy these meta tags and the CSS that needs to be added to the head of our page so I will grab these meta tags here and the bootstrap CSS and copy that and that needs to be added to the head of our page so I'll open back up our layout template which will affect our other templates since they inherit from them and within the head I'll actually put these above the title here so I will just paste those in and save that and now let's also copy the JavaScript that we need as well so I'm going to go back here and grab all of this JavaScript and copy that and we will paste that above the closing body tag of our layout so down here and our body I will paste in that JavaScript and save that and now let's use a bootstrap specific class to see if this works so I'm going to wrap our content in a div with the class of container which will give the content some good padding and spacing so I will do a div here and this div I will give a class equal to container which is a bootstrap class and now I will move our content inside of that container div and then I will clear up these here and simply adding in that CSS and JavaScript should be enough for our application to now be using bootstrap so if I go and reload our page and the browser now so I'm going to refresh this and I'm gonna do a hard refresh with command shift R which will also clear the cache so we can see that when I reloaded that the text changed and also the margins are also different and if I go to the about page so I'll do ford slash about and then we can see that text and margins are different on that page as well and it works on both of those pages because both templates are inheriting that single layout template okay so I know that's a lot to take in so let's do a quick recap before moving on to the next topic so we created a new template called layout dot HTML which we are seeing here and this

### [22:32](https://www.youtube.com/watch?v=QnDWIZuWYW0&t=1352s) Layout template

is our parent template that the others will inherit from so this has the main structure of our HTML that is going to be included on every page now you can have multiple blocks but right now we only have this single block down here called block content and we didn't have to call that block content we could have called it pretty much anything that we wanted but this content block is what the other templates are going to override and when they override the content block with data it will place that data at this location in the HTML so if we go to our home template then we can see we are extending the layout template and we are specifying that we want to put some information into our content block and that information is the dummy post data that we've seen before so when it's all said and done if I go to the home page in the browser and look at the page source here then we can see that we have all of this information from the layout template and then our two dummy blog posts are here in the container div which is where our content block was located okay so now that we have a base layout template in place let's add a navigation bar and some global styles to our website so that it looks a little nicer and similar to our final product that we saw before now this is a good bit of HTML so I'm going to grab this from some code snippets so you don't have to watch me type all of this out and the link to these code snippets will be in the description section below so you can grab these snippets as well now really you could fall along with these videos just fine without selling your application but having these in place will just give you a better idea for how this might look in a real finished application so let me open up my snippets folder here and I have this on my desktop so I'm gonna say from within sublime I'm going to open this and open this snippets folder on my desktop now the first snippet that I'm going to grab is in this file called navigation dot HTML so you can see I have a lot of HTML here with a lot of different bootstrap styles so I'm going to copy that and go back to our layout dot HTML file and I'm going to paste all of that information right below the opening body tag so I'll paste that in and get these intentions correct there so what we added here is a navigation bar with some bootstrap classes that will make this look nice and also is responsive so for example if you're on a smaller screen then it will resize everything appropriately okay and I'm also going to put in a new main section here that contains our content block and this snippet is in my main HTML folder so I'm going to bring this up close down that snippet and open up this main HTML snippet here and like I said I'll have links to these in the description sections below if you want to grab those as well so I'm going to copy this and we can see that we have our content block in here so I've got all of that copied I'm going to minimize this and in our layouts I'm going to replace our current container div and our current block content there and I'm going to replace that with what I just copied so we have this new container and I will indent those correctly and also I will remove the space here okay and I also have a few custom styles that aren't bootstrap specific and those are going to be in a file called main CSS now since this will be a CSS file in our actual project we'll need to put it somewhere and in flask static files like CSS and JavaScript need to be located in a static directory so let's create a directory in our project and call this static so I'll right click on my project here and do new folder and I will create this static folder which is all lowercase and then within our static folder I'm going to create our main dot CSS file so I'm going to say new file and this is going to be main dot CSS so I'll create that and within this main CSS I'm going to grab another snippet of code and in my snippets folder I called this main CSS so I will pull this up and do a control a to grab all of this it's not very long it's only 80 lines of custom styles so I will copy that and put that into our main CSS within our actual project okay and now that we have this main CSS file that we want to use now we have to include this in our layout template and we're going to need to use a new flask function here called URL 4 and URL 4 is a function that will find the exact location of routes for us so that we don't need to worry about it in the background so let's go back to our main application our flash blog PI and let's import that URL for function so up here in the imports from flask I will also import URL 4 and now back in our layout we can use this by coming up here to the head section of our website and we're going to want to add this style below the bootstrap styles so I'm going to grab the opening part of the bootstrap style there and I will now say that I want a new style sheet and this is going to be a type equal to text forged slash CSS and we can use the href to say where the CSS file is located now this is where we use that URL for function so I'm going to open up some double curly braces here so that we can write some code and I will say URL for and we want this to be a URL for our static directory and within our static directory we can pass in a another argument here of file name and we will set this file name equal to and I'll actually use single quotes here since we have double quotes on the outside and I'll just say equal to main dot CSS so now the style sheet at the top of our layout here is linking to this main dot CSS file within our static folder and our URL for function will take care of finding that exact location for us now it's a good idea to use URL for just about as many links as you can in your site so it would also be good for us to use this in our navigation as well but our navigation bar currently has two routes that we haven't created yet and we'll be creating those in the next video so we'll actually change those navigation links once those routes exist and at this point we should be pretty close to being done so if we reload our page in the browser let's see if all of these changes have taken effect and I might need to check and see if our web server is still running and it is so I can close this down and now reload our page then we can see that with those added snippets that this looks a lot nicer now there are only a few more touches that I'd like to add so it would be nice to visually split up these blog posts a bit and the main CSS file that we already added has some styles for that we just need to put in the correct HTML so within my snippets folder I have a file called article dot HTML so let me grab that snippet as well so I'm going to come over here and open up article HTML and I'm going to copy this and we

### [29:54](https://www.youtube.com/watch?v=QnDWIZuWYW0&t=1794s) Testing

can see here that this is just some updated code for how our post is displayed this is all of our post information that we had before with some additional HTML and styles so I'm going to put this within our loop for our blog post which is currently on our homepage so if I go back and open up our home template then this is the loop for our blog post here and instead of these h1 and paragraphs that we had before I'm just going to get rid of those and paste in our new code and I'll get this indentation correct here and save that ok so now if we save that and reload it in our browser then let's see what that looks like ok so now we can see that those blog posts are nice and split up a little bit better than they were before okay so this is all starting to come together and look a lot nicer so I think that is going to do it for this video I hope that now you have a good understanding of templates and how we can pass data into them and also the benefits of creating parent templates so that we can update every page on our site in a single location in the next video we'll be learning how to create and validate forms so that we can get started with creating some accounts and posting some real data to our website instead of just using this dummy data so if anyone has any questions about what we covered in this video then feel free to ask in the comment section below and I'll do my best to answer those and if you enjoyed these tutorials and would like to support them then there are several ways you can do that the easiest ways to simply like the video and give it a thumbs up and also it's a huge help to share these videos with anyone who you think would find them useful and if you have the means you can contribute through patreon and there's a link to that page in the description section below be sure to subscribe for future videos and thank you all for watching

---
*Источник: https://ekstraktznaniy.ru/video/12365*