Rendering Templates in Flask
Key Concepts
- Template Engine
- Template Inheritance
- Template Variables and Filters
Template Engine
Flask uses the Jinja2 template engine to render dynamic HTML pages. Jinja2 allows you to embed Python code within HTML, making it easier to generate content that varies based on user input or other conditions.
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') if __name__ == '__main__': app.run(debug=True)
Template Inheritance
Template inheritance allows you to create a base template that other templates can extend. This helps in maintaining a consistent layout across multiple pages. The base template defines common elements like headers and footers, while child templates can override specific blocks.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}Default Title{% endblock %}</title> </head> <body> <header> <h1>My Website</h1> </header> <main> {% block content %}{% endblock %} </main> <footer> <p>© 2023 My Website</p> </footer> </body> </html>
{% extends "base.html" %} {% block title %}Home Page{% endblock %} {% block content %} <h2>Welcome to the Home Page</h2> <p>This is the content of the home page.</p> {% endblock %}
Template Variables and Filters
Template variables allow you to pass data from your Flask application to your templates. Jinja2 provides filters to modify these variables. For example, you can use the |upper
filter to convert a string to uppercase.
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): name = "John Doe" return render_template('index.html', name=name) if __name__ == '__main__': app.run(debug=True)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home Page</title> </head> <body> <h1>Hello, {{ name|upper }}!</h1> </body> </html>
© 2024 Ahmed Baheeg Khorshid. All rights reserved.