Flask interview question · Most asked
How does Jinja2 templating work in Flask, including inheritance and autoescaping?
Summary
render_template('page.html', **context) renders Jinja2 templates from the templates/ folder. Templates support inheritance ({% extends %}, {% block %}), includes, macros and filters, and autoescaping is on for .html files.
Longer Answer
Autoescaping prevents XSS by escaping variables. |safe or Markup disables it, so only use them on trusted or sanitized HTML. Context processors (@app.context_processor) inject variables into all templates. Custom filters are registered with @app.template_filter().
Code Example
{# base.html #}
<html><body>{% block content %}{% endblock %}</body></html>
{# orders.html #}
{% extends "base.html" %}
{% block content %}
<h1>Orders for {{ user.name }}</h1>
{% for o in orders %}<li>{{ o.id }} - {{ o.total | round(2) }}</li>{% endfor %}
{% endblock %}
Key Points
- Template inheritance with blocks
- Autoescaping for
.html |safeonly for trusted HTML- Context processors and custom filters
More most-asked Flask questions
- How do you access request data and build responses in Flask?
- How do Flask sessions work and what are their security implications?
- What is the application factory pattern in Flask and why use it?
- What is Flask and what does 'microframework' mean?
- Explain Flask's application context and request context.
- What are Blueprints in Flask?
- How does routing work in Flask, including variable rules and HTTP methods?
- How do you use SQLAlchemy with Flask (Flask-SQLAlchemy 3.x)?