Structuring Your Project
00:00 Static files are essential for styling your website and making it more visually appealing. They are served directly to the client without any processing by Flask.
00:09
Generally, we place static files inside a folder named static/
at the project root or inside our app folder.
00:16
Go ahead and create a static/
folder in your board app.
00:24
In the static/
folder, create a new file called styles.css
, which will include the CSS to style your Flask project.
00:32
In the next section, we will add some CSS in this file, but for now, let’s see how you can include this in our base.html
file so that it is included in all the child pages that inherit from the base template.
00:49
The url_for()
function is Flask’s way of generating the correct URL for the file you want to include. When you used it with templates earlier, Flask looked for the route associated with your child templates and generated the URL for that route.
01:04
But static files like CSS, JavaScript or images work a bit differently. They don’t have routes. Instead, Flask serves them from a special directory called static/
.
01:15
That’s why when working with static files, you pass static
as the first argument to url_for()
. This tells Flask to look into the static/
directory to find the file being referenced.
01:26
The second argument, filename
, specifies the file name inside the static/
folder. In this case, it’s styles.css
. Flask then generates the correct URL to this file based on your project structure and where it’s running.
01:41
Here’s the key difference between using url_for()
with templates and with static files. With templates, you pass a namespace string like pages.about
, which corresponds to a route in your application. With static files, you pass static
and then the file name.
01:57
There’s no namespace involved because static files are served directly from the static/
folder. The link
tag in your base.html
file ensures that the CSS file is applied to all the templates that extend from it.
02:11 That’s why you’ll see the styles you have created appear across your entire message board project.
Become a Member to join the conversation.