0
0
FlaskHow-ToBeginner · 4 min read

How to Use Jinja2 Templates in Flask for Dynamic Web Pages

In Flask, you use Jinja2 templates by placing HTML files with Jinja syntax in a templates folder and rendering them with render_template(). You pass data from your Flask route to the template, which dynamically generates HTML to send to the browser.
📐

Syntax

Flask uses render_template('template.html', key=value) to load a Jinja2 template file and pass variables to it. Inside the template, you use {{ variable }} to display values and {% %} for control statements like loops and conditions.

  • render_template(): Loads and renders the HTML template.
  • templates/ folder: Where you store your Jinja2 HTML files.
  • {{ variable }}: Inserts Python data into HTML.
  • {% for item in list %}...{% endfor %}: Loop over data.
html
<!DOCTYPE html>
<html>
  <head><title>{{ title }}</title></head>
  <body>
    <h1>{{ heading }}</h1>
    <ul>
      {% for item in items %}
        <li>{{ item }}</li>
      {% endfor %}
    </ul>
  </body>
</html>
💻

Example

This example shows a simple Flask app that renders a Jinja2 template with a title, heading, and a list of items passed from the Python code.

python
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    data = {
        'title': 'My Flask Page',
        'heading': 'Welcome to Flask with Jinja2',
        'items': ['Apple', 'Banana', 'Cherry']
    }
    return render_template('index.html', **data)

if __name__ == '__main__':
    app.run(debug=True)
Output
<!DOCTYPE html> <html> <head><title>My Flask Page</title></head> <body> <h1>Welcome to Flask with Jinja2</h1> <ul> <li>Apple</li> <li>Banana</li> <li>Cherry</li> </ul> </body> </html>
⚠️

Common Pitfalls

Common mistakes when using Jinja2 in Flask include:

  • Not placing templates inside a templates folder at the project root.
  • Forgetting to pass variables to render_template(), causing {{ variable }} to be empty.
  • Using incorrect Jinja syntax like missing %} or }} braces.
  • Trying to use Python code directly inside templates instead of Jinja syntax.
python
Wrong:
return render_template('index.html')  # no variables passed

Right:
return render_template('index.html', title='Hello', items=[1,2,3])
📊

Quick Reference

FeatureUsageExample
Render templaterender_template('file.html', var=value)render_template('index.html', name='Alice')
Insert variable{{ variable }}{{ name }}
For loop{% for item in list %}...{% endfor %}{% for fruit in fruits %}
  • {{ fruit }}
  • {% endfor %}
    If condition{% if condition %}...{% endif %}{% if user %}Hello {{ user }}{% endif %}
    Comment{# comment #}{# This is a comment #}

    Key Takeaways

    Place your Jinja2 HTML files inside a 'templates' folder in your Flask project.
    Use render_template() in Flask routes to load templates and pass data.
    Use {{ }} to insert variables and {% %} for logic like loops and conditions in templates.
    Always pass needed variables to render_template to avoid empty placeholders.
    Check your Jinja syntax carefully to prevent template errors.