Dynamic Content

Tutorial 3 of 4

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

  1. Exercise: Create a Flask application that displays the current date and time on the webpage. (Hint: Use Python's datetime module 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 }}

```

  1. 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!