BudiBadu Logo
Samplebadu

Flask by Example: Template Context Data

Flask 3.0+

Passing data from your Python view functions to your HTML templates is the core of dynamic web pages. This demonstrates how to pass variables and access them securely.

Code

from flask import Flask, render_template

app = Flask(__name__)

class User:
    def __init__(self, name):
        self.name = name
        self.is_admin = True

@app.route('/profile')
def profile():
    # 1. Simple variables
    title = "User Profile"
    
    # 2. Complex objects
    user = User("Alice")
    
    # 3. Dictionaries
    stats = {'posts': 12, 'followers': 500}
    
    # Pass data as keyword arguments to render_template
    return render_template('profile.html', 
                         page_title=title,
                         user=user,
                         stats=stats)

# --- profile.html ---
# <h1>{{ page_title }}</h1>
# <p>Welcome, {{ user.name }}!</p>
# <p>Followers: {{ stats.followers }}</p>
# <p>Is Admin: {{ user.is_admin }}</p>
# 
# <!-- Safe HTML rendering (use with caution) -->
# {{ "<strong>Bold Text</strong>" | safe }}

Explanation

The render_template() function passes keyword arguments to the template context, making variables available for use in your HTML. Jinja2 uses dot notation (e.g., user.name) to access attributes or dictionary keys, which simplifies the syntax compared to Python.

Security is a built-in feature of Jinja2. It automatically escapes all variables before rendering them, which effectively prevents Cross-Site Scripting (XSS) attacks by converting special characters into HTML entities.

If you explicitly want to render raw HTML from a trusted source, you must use the | safe filter. Use this with extreme caution, and never apply it to unsanitized user input.

Code Breakdown

22
render_template('profile.html', ...) looks for the file in the templates folder. The subsequent arguments define the context.
28
{{ page_title }} outputs the value of the page_title variable. If the variable is missing, Jinja prints nothing (it doesn't crash).
30
{{ stats.followers }} demonstrates dot notation. In Python, this is a dictionary lookup stats['followers'], but in Jinja, you use the dot.
34
| safe disables auto-escaping. Only use this if you trust the source of the HTML string (e.g., it comes from your own database, not user input).