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
  • |safe only for trusted HTML
  • Context processors and custom filters

More most-asked Flask questions

← All Flask questions