Templates and Static Files in Flask
Key Concepts
- Templates
- Static Files
- Template Inheritance
Templates
Templates in Flask are used to create dynamic HTML pages. They allow you to separate the presentation logic from the business logic. Flask uses the Jinja2 templating engine, which enables you to embed Python code within HTML to generate dynamic content.
For example, you can create a template file named index.html
and use it to render dynamic content. The template can include placeholders for variables, loops, and conditional statements.
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html', title='Home', message='Welcome to our site!') if __name__ == '__main__': app.run()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ title }}</title> </head> <body> <h1>{{ message }}</h1> </body> </html>
Static Files
Static files in Flask include CSS, JavaScript, images, and other resources that do not change dynamically. These files are stored in a directory named static
and can be accessed using a URL prefix of /static
.
For instance, if you have a CSS file named styles.css
in the static
directory, you can link it in your HTML template as follows:
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
This allows you to keep your static resources organized and easily accessible in your web application.
Template Inheritance
Template inheritance in Flask allows you to create a base template that other templates can extend. This is useful for reusing common elements across multiple pages, such as headers, footers, and navigation menus.
For example, you can create a base template named base.html
that includes a common structure and placeholders for content:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}Default Title{% endblock %}</title> <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}"> </head> <body> <header> <h1>My Website</h1> </header> <main> {% block content %}{% endblock %} </main> <footer> <p>© 2023 My Website</p> </footer> </body> </html>
You can then create a child template named index.html
that extends the base template and fills in the content blocks:
{% extends "base.html" %} {% block title %}Home{% endblock %} {% block content %} <h2>Welcome to the Homepage</h2> <p>This is the content of the homepage.</p> {% endblock %}
This approach ensures consistency across your web application while allowing for flexibility in content.