Flask / Flask Templates and Jinja2
Dynamic Content
In this tutorial, you'll learn how to use Flask and Jinja2 to create dynamic content in your web pages. This will involve using template variables to inject Python data into your …
Section overview
4 resourcesExplains how to use Flask templates and Jinja2 for dynamic content rendering.
Introduction
In this tutorial, we will explore how to create dynamic web content using Flask and the Jinja2 templating language. Dynamic web content refers to web content that changes based on the behavior, preferences, and interests of the user. By the end of this tutorial, you will learn how to inject Python data into your HTML using template variables.
Prerequisites
- Basic understanding of Python
- Familiarity with HTML
- Flask and Jinja2 installed. If you haven't installed them, you can do so by running the following command in your terminal:
pip install flask jinja2
Step-by-Step Guide
Flask is a micro web framework written in Python. It's lightweight and modular, making it adaptable to developers' needs. Jinja2 is a templating language for Python, modeled after Django's templates. It is used in Flask to create dynamic web content.
Flask Basics
A basic flask application looks like this:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
When you navigate to the root URL, you should see the text 'Hello, World!'.
Creating Dynamic Content with Jinja2
Jinja2 allows us to inject data into our HTML templates. Here's an example:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/greet/<name>')
def greet(name):
return render_template('greet.html', name=name)
if __name__ == '__main__':
app.run()
In the HTML template (greet.html), we can access the variable name like this: {{ name }}.
Code Examples
Example 1: Passing a Single Variable
Here's a simple Flask application that passes a single variable to a template.
Python code (app.py):
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/greet/<name>')
def greet(name):
# Pass the 'name' variable to the template
return render_template('greet.html', name=name)
if __name__ == '__main__':
app.run()
HTML Template (templates/greet.html):
<!DOCTYPE html>
<html>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>
The {{ name }} in the HTML template is replaced with the value of the name variable passed from the Flask app.
Example 2: Passing a List
We can also pass more complex data types, like lists, to our templates.
Python code (app.py):
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/greet')
def greet():
names = ['Alice', 'Bob', 'Charlie']
# Pass the 'names' list to the template
return render_template('greet.html', names=names)
if __name__ == '__main__':
app.run()
HTML Template (templates/greet.html):
<!DOCTYPE html>
<html>
<body>
{% for name in names %}
<h1>Hello, {{ name }}!</h1>
{% endfor %}
</body>
</html>
In this case, Jinja2 will loop over the names list and generate a greeting for each name.
Summary
In this tutorial, we have covered how to create dynamic web content using Flask and Jinja2. We've learnt how to pass data from our Flask app to our HTML templates using Jinja2's templating syntax.
Practice Exercises
- Exercise: Create a Flask application that displays the current date and time on the webpage. (Hint: Use Python's
datetimemodule to get the current date and time)
Solution: Python code (app.py):
```python
from flask import Flask, render_template
from datetime import datetime
app = Flask(name)
@app.route('/')
def display_time():
now = datetime.now()
return render_template('time.html', time=now)
if name == 'main':
app.run()
HTML Template (`templates/time.html`):html
Current date and time: {{ time }}
```
- Exercise: Extend the greeting Flask application to also display the user's age.
Solution: Python code (app.py):
```python
from flask import Flask, render_template
app = Flask(name)
@app.route('/greet/
def greet(name, age):
return render_template('greet.html', name=name, age=age)
if name == 'main':
app.run()
HTML Template (`templates/greet.html`):html
Hello, {{ name }}! You are {{ age }} years old.
```
Keep practicing to get a good grip on Flask and Jinja2. You can try creating more complex web applications by integrating Flask with databases, creating user login systems, etc. Happy coding!
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Random Password Generator
Create secure, complex passwords with custom length and character options.
Use toolLatest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article