Jinja2 Templating
Jinja2 is a fast, expressive templating engine for Python. It is the default template engine in Flask and can also be used standalone or with other framewo...
Dynamic HTML with Jinja2 Templates
Jinja2 is a fast, expressive templating engine for Python. It is the default template engine in Flask and can also be used standalone or with other frameworks. Jinja2 lets you embed Python-like expressions and logic inside HTML files to generate dynamic content.
Jinja2 syntax uses three delimiters: - {{ expression }} — outputs a variable or expression - {% statement %} — control flow: for, if, block, extends - {# comment #} — ignored by the renderer
Variables: In your Python view: render_template('page.html', user=current_user, items=products) In the template: <h1>Hello, {{ user.username }}!</h1> <p>You have {{ items|length }} items.</p>
Filters transform variables using the pipe character: {{ name|upper }} <!-- ALICE --> {{ price|round(2) }} <!-- 9.99 --> {{ text|truncate(100) }} <!-- first 100 chars... --> {{ html_content|safe }} <!-- render HTML without escaping -->
Control structures: {% for product in products %} <div class="card"> <h2>{{ product.name }}</h2> <p>{{ product.price | round(2) }}</p> </div> {% else %} <p>No products available.</p> {% endfor %}
{% if user.is_authenticated %} <a href="/logout">Logout</a> {% elif user.is_guest %} <a href="/login">Login</a> {% else %} <a href="/register">Register</a> {% endif %}
Template inheritance eliminates duplication. Define a base layout: <!-- base.html --> <!DOCTYPE html> <html> <head><title>{% block title %}My Site{% endblock %}</title></head> <body> {% block content %}{% endblock %} </body> </html>
<!-- child.html --> {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <h1>Welcome!</h1> {% endblock %}
Macros are reusable template fragments, similar to functions: {% macro input_field(name, label, type='text') %} <label>{{ label }}: <input type="{{ type }}" name="{{ name }}"></label> {% endmacro %} {{ input_field('email', 'Email Address', type='email') }}
Practical tip: Use {{ variable|default('N/A') }} to provide fallback values for variables that might not exist. This prevents UndefinedError exceptions in templates and is cleaner than if/else checks.
Exam tip: Jinja2 auto-escapes HTML by default when used with Flask (autoescape=True). This prevents XSS attacks. The |safe filter disables escaping for a specific variable — use it only for content you trust completely.