Practical Python Programming · Useful Tools and Libraries — Flask Routing and Templates

The two core features of Flask:

  • Routing: Mapping URLs to Python functions
  • Template: Jinja2 template system for rendering HTML pages

You will learn how to build web pages, pass values, template inheritance, static files, and other core knowledge.

Part One: Flask Routing

1. What is Routing?

Routing defines which function should handle a given URL:

@app.route('/hello')
def hello():
    return "Hello Flask!"

Access:

http://127.0.0.1:5000/hello

2. Basic Routing Syntax

@app.route('/')
def index():
    return "Home Page"

3. Routing Parameters

Flask can receive variables in the URL.

String Parameters (default)

@app.route('/user/<name>')
def user(name):
    return f"Hello, {name}"

Access:<span>/user/Alice</span>

Converters (int / float / path, etc.)

Type Usage
<span>string</span> Default type
<span>int</span> Integer
<span>float</span> Decimal
<span>path</span> Path including <span>/</span>
<span>uuid</span> UUID type

Example:

@app.route('/add/<int:a>/<int:b>')
def add(a, b):
    return str(a + b)

4. HTTP Method Restrictions (GET / POST, etc.)

@app.route('/login', methods=['GET', 'POST'])
def login():
    return "login"

5. URL Reverse Generation (url_for)

It is recommended to use <span>url_for()</span> to avoid hardcoding URLs.

from flask import url_for

@app.route('/home')
def home():
    return url_for('home')   # "/home"

You can also use it in templates:

<a href="{{ url_for('home') }}">Home</a>

Part Two: Template System (Jinja2)

Flask uses the Jinja2 template engine by default, which is powerful, secure, and flexible.

1. Template Directory Structure

Flask will automatically look for templates in <span>templates/</span>.

project/
  app.py
  templates/
    index.html
    about.html

2. The Simplest Template Rendering

from flask import render_template

@app.route('/page')
def page():
    return render_template("index.html")

<span>templates/index.html</span>:

<h1>Hello Template</h1>

3. Passing Variables to Templates

@app.route('/user/<name>')
def user(name):
    return render_template("user.html", username=name)

<span>templates/user.html</span>:

<h1>Hello {{ username }}</h1>

4. Control Statements in Templates

Conditional Statements

{% if vip %}
  <p>Valued VIP User</p>
{% else %}
  <p>Regular User</p>
{% endif %}

✔ Loops

<ul>
{% for item in items %}
  <li>{{ item }}</li>
{% endfor %}
</ul>

5. Jinja2 Filters

Common filters:

{{ "hello"|upper }}   <!-- HELLO -->
{{ 3.14159|round(2) }} <!-- 3.14 -->

6. Template Inheritance (Recommended)

Very powerful, can avoid duplicate HTML.

✔ base.html (Master Template)

<span>templates/base.html</span>:

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}Flask Demo{% endblock %}</title>
</head>
<body>
    <div class="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>

Child Template Inheritance

<span>templates/index.html</span>:

{% extends "base.html" %}

{% block title %}Home Page{% endblock %}

{% block content %}
<h1>Welcome to the Home Page</h1>
{% endblock %}

7. Using Static Files (CSS/JS/Images)

Default directory:<span>static/</span>

project/
  static/
    style.css

In templates:

<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">

8. Passing Data to Frontend Templates (Comprehensive Example)

<span>app.py</span>:

@app.route('/products')
def products():
    items = ["Computer", "Phone", "Headphones"]
    return render_template("products.html", items=items, vip=True)

<span>products.html</span>:

{% extends "base.html" %}

{% block content %}
    <h1>Product List</h1>
    <ul>
    {% for item in items %}
        <li>{{ item }}</li>
    {% endfor %}
    </ul>

    {% if vip %}
        <p>VIP users enjoy a 10% discount!</p>
    {% endif %}
{% endblock %}

Conclusion

You have mastered the core of Flask web development:

✔ Routing System

  • • Define URLs
  • • Routing Parameters
  • • HTTP Methods
  • <span>url_for</span> Reverse Resolution

✔ Template System (Jinja2)

  • • Load Templates
  • • Pass Variables
  • • Conditions / Loops
  • • Template Inheritance
  • • Load Static Files

You can definitely develop a small web site or management backend!

Leave a Comment