0
0
Flaskframework~5 mins

Variable substitution syntax in Flask

Choose your learning style9 modes available
Introduction

Variable substitution lets you show dynamic data inside your web pages easily. It replaces placeholders with real values when the page loads.

Showing a user's name on a welcome page.
Displaying a list of items from a database.
Updating page content based on user input.
Showing the current date or time dynamically.
Syntax
Flask
{{ variable_name }}

Use double curly braces {{ }} to insert variables.

Variables come from the Flask code you send to the template.

Examples
Shows the value of the variable username in the page.
Flask
{{ username }}
Shows the age property of the user object.
Flask
{{ user.age }}
Shows the result of a simple expression, here it will show 8.
Flask
{{ 5 + 3 }}
Concatenates strings and variables to show a greeting.
Flask
{{ 'Hello ' + username }}
Sample Program

This Flask app shows how to use variable substitution to greet a user by name. The variable name is replaced with the value of user_name when rendering the page.

Flask
from flask import Flask, render_template_string

app = Flask(__name__)

@app.route('/')
def home():
    user_name = 'Alice'
    html = '''
    <html lang="en">
    <head><title>Welcome</title></head>
    <body>
        <h1>Welcome, {{ name }}!</h1>
        <p>We are glad to see you.</p>
    </body>
    </html>
    '''
    return render_template_string(html, name=user_name)

if __name__ == '__main__':
    app.run(debug=False, port=5000)
OutputSuccess
Important Notes

Variable substitution is safe by default: Flask escapes HTML to prevent security issues.

You can use filters like {{ variable|upper }} to change output style.

Common mistake: forgetting to pass the variable from Flask to the template causes empty output.

Summary

Use {{ variable }} to insert dynamic data in Flask templates.

Variables come from your Flask code when rendering the template.

This makes your web pages interactive and personalized.