Frontend and Backend Collaboration: Flask Template Rendering HTML Dynamic Data Example

In web development, collaboration between the front and back ends is crucial. The back end handles data and logical operations, while the front end presents data in a user-friendly manner. Python’s Flask framework provides a concise template rendering feature, enabling easy implementation of dynamic display of back-end data on front-end pages. This article will guide beginners through a simple example to understand how Flask connects the front and back ends to complete data rendering.

1. Preparation: Install Flask and Project Structure

First, ensure Python is installed (version 3.6+ is recommended), then install Flask via pip:

pip install flask

Create a simple project structure to store code and template files:

my_flask_app/
├── app.py          # Main back-end program
└── templates/      # Folder for HTML templates
    └── index.html  # Front-end template file

Note: templates is Flask’s default template directory. All HTML templates must be placed here; otherwise, Flask won’t find them.

2. Back-End Basics: Define Routes and View Functions

The core of the back-end code (app.py) uses routes (@app.route) to define access paths and prepares data for rendering in view functions.

# app.py
from flask import Flask, render_template  # Import Flask core class and template rendering tool

app = Flask(__name__)  # Create Flask application instance

# Define the root route; accessing http://localhost:5000 triggers this
@app.route('/')
def index():
    # 1. Prepare back-end data (simulate complex data with a user info dictionary)
    user_info = {
        "name": "Xiaoming",
        "age": 20,
        "hobbies": ["Basketball", "Programming", "Reading"],  # List for loop rendering
        "is_student": True  # Boolean for conditional rendering
    }

    # 2. Render template and pass data
    # render_template automatically finds index.html in the templates folder
    # and passes the user_info variable to the front-end template
    return render_template('index.html', user=user_info)

# Start the application (debug=True enables auto-reload on code changes)
if __name__ == '__main__':
    app.run(debug=True)

Key Concepts:
- Route: @app.route('/') defines the access path. When a user visits http://localhost:5000, the following view function is triggered.
- View Function: index() processes the request and returns a rendered template (via render_template).
- Template Rendering: render_template('index.html', user=user_info) injects back-end data (user_info) into the front-end template, generating the final HTML page.

3. Front-End Template: Display Dynamic Data with Jinja2 Syntax

The template file (templates/index.html) uses Flask’s template engine (Jinja2) to inject back-end data into HTML. Here’s the complete template code:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>User Info</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; }
        .info { border: 1px solid #ddd; padding: 20px; border-radius: 5px; }
        .hobbies { margin-top: 10px; }
        .hobbies ul { list-style: none; padding: 0; }
        .hobbies li { margin: 5px 0; }
    </style>
</head>
<body>
    <div class="info">
        <!-- 1. Display basic variables -->
        <h1>Welcome, {{ user.name }}!</h1>
        <p><strong>Age:</strong> {{ user.age }} years old</p>

        <!-- 2. Conditional rendering (based on is_student value) -->
        {% if user.is_student %}
            <p>Status: <span style="color: green;">Student</span></p>
        {% else %}
            <p>Status: <span style="color: red;">Graduated</span></p>
        {% endif %}

        <!-- 3. Loop through list data -->
        <div class="hobbies">
            <h3>Hobbies:</h3>
            <ul>
                {% for hobby in user.hobbies %}
                    <li>{{ hobby }}</li>
                {% endfor %}
            </ul>
        </div>
    </div>
</body>
</html>

4. Code Explanation: Jinja2 Syntax in Templates

The template uses Flask’s built-in Jinja2 engine to dynamically render data with special syntax:

  1. Variable Output: {{ user.name }}
    The name key from the user dictionary passed by the back end is replaced with the actual value (e.g., “Xiaoming”).

  2. Conditional Judgment: {% if user.is_student %}
    Based on the boolean value is_student from the back end, the template displays different content (“Student” or “Graduated”).

  3. Loop Rendering: {% for hobby in user.hobbies %}
    The hobbies list from the back end is iterated, and each element (e.g., “Basketball”) generates an <li> tag.

5. Run and Verify

  1. Open the command line in the project root (my_flask_app) and run:
   python app.py
  1. Visit http://localhost:5000 in your browser. You will see:
    - Welcome message (Xiaoming)
    - Age (20 years old)
    - Status (Student)
    - Hobbies list (Basketball, Programming, Reading)

6. Extensions and Considerations

  1. Pass More Data: Try defining multiple data structures (e.g., user and posts list) and render them simultaneously in the template.
  2. Optimize Conditional Logic: Use {% if ... elif ... else %} for multi-condition displays.
  3. Template Reuse: Split HTML structure (e.g., navigation, footer) using {% include %} or {% extends %} to reduce redundancy.

With this example, you’ve mastered the core process of Flask template rendering: back-end data preparation → template passing → front-end dynamic display via Jinja2. This is the foundation of front-back end collaboration in web development. For advanced topics, explore Flask form handling, database interaction, etc.

Xiaoye