0
0
FlaskHow-ToBeginner · 3 min read

How to Use Templates in Flask: Simple Guide with Examples

In Flask, you use render_template to load HTML files called templates from the templates folder and send dynamic data to them. Templates use the Jinja2 syntax to insert variables and control flow inside HTML, making your web pages dynamic and reusable.
📐

Syntax

Flask uses the render_template function to render HTML templates stored in the templates folder. You pass the template filename and any variables as keyword arguments.

  • render_template('filename.html', var1=value1, var2=value2): loads the template and injects variables.
  • Templates use Jinja2 syntax like {{ variable }} to display values and {% %} for logic.
python
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    name = 'Alice'
    return render_template('index.html', user_name=name)
💻

Example

This example shows a Flask app rendering a template that greets a user by name. The template uses {{ user_name }} to insert the variable.

python
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    user_name = 'Alice'
    return render_template('greet.html', user_name=user_name)

# Template file: templates/greet.html
# ----------------------------------
# <!DOCTYPE html>
# <html lang="en">
# <head><title>Greeting</title></head>
# <body>
#   <h1>Hello, {{ user_name }}!</h1>
# </body>
# </html>
Output
<h1>Hello, Alice!</h1>
⚠️

Common Pitfalls

  • Not placing templates inside a folder named templates causes Flask to fail finding them.
  • Forgetting to pass variables to render_template leads to empty or error outputs.
  • Using incorrect Jinja2 syntax like missing curly braces {{ }} or wrong tags {% %} causes template errors.
python
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    # Wrong: template file outside 'templates' folder or typo in filename
    # return render_template('greet.htm', user_name='Alice')

    # Correct:
    return render_template('greet.html', user_name='Alice')
📊

Quick Reference

Remember these key points when using templates in Flask:

  • Templates must be in a folder named templates at your project root.
  • Use render_template('file.html', var=value) to render templates with variables.
  • Use Jinja2 syntax {{ variable }} to insert data and {% %} for logic inside templates.
  • Keep HTML and Python code separate for cleaner, maintainable apps.

Key Takeaways

Always put your HTML templates inside a folder named 'templates' in your Flask project.
Use render_template with the template filename and variables to render dynamic pages.
Templates use Jinja2 syntax: {{ variable }} for data and {% %} for logic like loops or conditions.
Passing variables to templates lets you customize content dynamically.
Check template filenames and syntax carefully to avoid common errors.