Conteúdo do Curso
Flask Intensive Course: Web Development with Python
Flask Intensive Course: Web Development with Python
Static Files
Alright, let's dive into the fun part: including your static files in our Flask app.
Static files are like your app's fashion statement – it's all about the style (CSS) and a bit of personality (JavaScript). These files are the static, unchanging backbone of your site, unlike the dynamic HTML files.
First, we're going to get organized. Create a new folder and name it static. Within this folder, create another one called css, and inside that, craft your masterpiece with a file named main.css. Your directory structure should now be as follows: static, css, and main.css.
With this stylish structure, we'll jazz up the fonts and colors to see the magic happen.
As each template inherits the structure of base.html, we can directly modify the links to static files within this central template. To do this, insert a <link>
tag within the <head>
section. This change will be applied to the body of every page since we are modifying the <body>
tag.
The file's name in the example below doesn't correspond to the file's name in our project.
index
index
index
It will be applied in the body of every page since we are changing the base.html. And if we are going to inspect the web page and go down, you can see the font and color. You can turn these styles on and off here.
For JavaScript, create a new folder inside static directory called js. Inside the js directory, create a new file named main.js and include your JavaScript code, similar to what you did with CSS.
A better practice is to use a URL path. It's more robust in getting the static location instead of writing out the entire URL path manually. We will use this Jinga syntax.
First, define the top-level directory and then specify the file name. The url_for
function will automatically generate or evaluate the complete path.
The file's name in the example below doesn't correspond to the file's name in our project.
index
index
index
So, this is how you should link static files using url_for
and Jinga2 syntax.
Obrigado pelo seu feedback!