Home > Courses > Flask: Python Web Development > Static Files in Flask and More on Jinja Template

Static Files in Flask and More on Jinja Template

Subject: Flask: Python Web Development
Static Files in Flask
Static files are files served by a web server and do not change over time like CSS and Javascript files (may also include images and videos) use in web development to improve user experience.

Step 1.
Create the "static" folder if you have not done so. Remember in the last topic when creating the "templates" folder we are ask to also create the "static" folder as well.

Step 2.
Create a CSS file name style.css inside the "static" folder.
static/style.css
And have it's content as follows.

h2{ 
  color: green;
}
body {
  background-color: lightblue;
}

Remember, this is just a minimal style to learn about static, see my course on CSS to learn more about.

Step 3.
Now open the index.html file in the "templates" folder and use the special 'static' endpoint name to generate URLs for static files i.e the style.css
url_for('static', filename='style.css')


 <!DOCTYPE html>
<html>
<head>
    <title>TEA Learn</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h2>Welcome to Flask class</h2>
    <p>
      This course is about building web application using Python and Flask</p>
 </body>
 </html>


Step 4.
Open the app.py and run Flask app

More on Jinja
Remember the team dynamic route in the previous topic, we can also extend that program so that in case if the user did not add a name to the end of the URL our program can handle that.

Example
instead of entering the URL like this
http://127.0.0.1:5000/team/Emeka

Someone did this (with no name in the URL)
http://127.0.0.1:5000/team

Modify the app.py

...
@app.route('/team/')
@app.route('/team/<name>')
def team(name=None):
       return render_template("about.html", myname=name)
...

This shows how to handle a dynamic route with or without a value for it's function argument (None)

And modify the about.html file too...
templates/about.html

 <!DOCTYPE html>
<html>
<head>
    <title>TEA Learn Team</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
{% if myname %}
  <h2>Welcome, {{ myname }}!</h2>
{% else %}
  <h2>Welcome to TEA Learn</h2>
{% endif %}
 </body>
 </html>


This shows how we can use conditional statement in Jinja template.

See the attached screenshots.

Site structure with templates and static folder with files




Our Python file app.py




http://127.0.0.1:5000/team/Onuorah




http://127.0.0.1:5000/team/Abiodun




http://127.0.0.1:5000/team





By: Benjamin Onuorah

Comments

No Comment yet!

Login to comment or ask question on this topic


Previous Topic Next Topic

Supported by