How to Send Data to a Flask Template with Examples

Sending data to a Flask template is a fundamental part of web development with Flask. This guide will show you how to pass student details from your Flask backend to a template for rendering. We will cover setting up the Flask application, creating routes, defining templates, and passing data from the backend to the frontend.

 

 

How to Send Data to a Flask Template with Examples

 

 

Setting Up the Flask Application

 

Install Flask using pip: 


pip install flask



Creating the Template

 

send data to a flask template

 



Create a folder named `templates` in the same directory as `app.py`. Inside this folder, create a file named `students.html`:

 

 


<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <title>Student List</title>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="{{ url_for('index') }}">Student App</a>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a class="nav-link" href="{{ url_for('student_list') }}">Students</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{{ url_for('add_student') }}">Add Student</a>
                </li>
            </ul>
        </div>
    </nav>
    <div class="container mt-5">
        <h1>Student List</h1>
        <ul class="list-group">
            {% for student in students %}
                <li class="list-group-item">{{ student.name }} - Age: {{ student.age }} - Major: {{ student.major }}</li>
            {% endfor %}
        </ul>
    </div>
</body>
</html>



Create the Flask Application and Defining the Student Data

 

Let's assume you have a list of student details that you want to pass to a template. This data can be hard-coded or fetched from a database.

 

For simplicity, let's use hard-coded data:

 


students = [
        {'name': 'kumar', 'age': 20, 'major': 'Computer Science'},
        {'name': 'riyas', 'age': 22, 'major': 'Mathematics'},
        {'name': 'priya', 'age': 23, 'major': 'Physics'}
    ]



Creating a Route and Passing Data

 

Modify the `index` route to pass the `students` data to a template:

 


@app.route('/students')
def student_list():
    students = [
        {'name': 'kumar', 'age': 20, 'major': 'Computer Science'},
        {'name': 'riyas', 'age': 22, 'major': 'Mathematics'},
        {'name': 'priya', 'age': 23, 'major': 'Physics'}
    ]
    return render_template('students.html', students=students)



index.html



<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <title>Home</title>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="{{ url_for('index') }}">Student App</a>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a class="nav-link" href="{{ url_for('student_list') }}">Students</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{{ url_for('add_student') }}">Add Student</a>
                </li>
            </ul>
        </div>
    </nav>
    <div class="container mt-5">
        <h1>Welcome to the Student App</h1>
    </div>
</body>
</html>



send data to a flask template


 

Read also:
 

 

 

Here is the complete `app.py` file for reference:

 


from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)


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


@app.route('/students')
def student_list():
    students = [
        {'name': 'kumar', 'age': 20, 'major': 'Computer Science'},
        {'name': 'riyas', 'age': 22, 'major': 'Mathematics'},
        {'name': 'priya', 'age': 23, 'major': 'Physics'}
    ]
    return render_template('students.html', students=students)


if __name__ == '__main__':
    app.run(debug=True)



This template uses Jinja2 templating syntax to iterate over the `students` list and display each student's details.
 

Run your Flask application:


python app.py

Navigate to `http://127.0.0.1:5000/students` in your web browser, and you should see a list of students displayed on the page. 

 

Add Update Pages and Send Data to a Flask Template with Examples


To add input fields for `name`, `age`, and `major` in a form and display the submitted data on a result page, follow these steps:

1. Set up the form to accept user input.
2. Handle the form submission on the server-side and pass the data to a result template.


Template for the Form: `add_student.html`

 

send data to a flask template

 



Create this file in the `templates` directory:

 

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <title>Add Student</title>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="{{ url_for('index') }}">Student App</a>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a class="nav-link" href="{{ url_for('student_list') }}">Students</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{{ url_for('add_student') }}">Add Student</a>
                </li>
            </ul>
        </div>
    </nav>
    <div class="container mt-5">
        <h1>Add Student</h1>
        <form method="POST" action="{{ url_for('add_student') }}">
            <div class="form-group">
                <label for="name">Name:</label>
                <input type="text" class="form-control" id="name" name="name" required>
            </div>
            <div class="form-group">
                <label for="age">Age:</label>
                <input type="number" class="form-control" id="age" name="age" required>
            </div>
            <div class="form-group">
                <label for="major">Major:</label>
                <input type="text" class="form-control" id="major" name="major" required>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
</body>
</html>



Template for the Result Page: `student_result.html`

 


<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <title>Student Result</title>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="{{ url_for('index') }}">Student App</a>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a class="nav-link" href="{{ url_for('student_list') }}">Students</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{{ url_for('add_student') }}">Add Student</a>
                </li>
            </ul>
        </div>
    </nav>
    <div class="container mt-5">
        <h1>Student Details</h1>
        <p>Name: {{ name }}</p>
        <p>Age: {{ age }}</p>
        <p>Major: {{ major }}</p>
        <a href="{{ url_for('add_student') }}" class="btn btn-primary">Add Another Student</a>
    </div>
</body>
</html>


Full Summary 'app.py'

 


from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)


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


@app.route('/students')
def student_list():
    students = [
        {'name': 'kumar', 'age': 20, 'major': 'Computer Science'},
        {'name': 'riyas', 'age': 22, 'major': 'Mathematics'},
        {'name': 'priya', 'age': 23, 'major': 'Physics'}
    ]
    return render_template('students.html', students=students)


@app.route('/add_student', methods=['GET', 'POST'])
def add_student():
    if request.method == 'POST':
        name = request.form['name']
        age = request.form['age']
        major = request.form['major']
        return redirect(url_for('student_result', name=name, age=age, major=major))
    return render_template('add_student.html')


@app.route('/student_result')
def student_result():
    name = request.args.get('name')
    age = request.args.get('age')
    major = request.args.get('major')
    return render_template('student_result.html', name=name, age=age, major=major)


if __name__ == '__main__':
    app.run(debug=True)


This setup allows you to:


1. Display a form for the user to enter student details (`name`, `age`, and `major`).
2. Handle the form submission, process the data, and redirect to a result page.
3. Display the submitted data on the result page.

 

send data to a flask template

 



By following these steps, you can collect user input through a form, process it on the server-side, and display the results dynamically on a new page.

 

By following these steps, you can easily pass data from your Flask backend to your templates and render dynamic content based on that data. This guide covers the basics, and you can expand it further by integrating a database, handling forms, and more.


Previous Post Next Post