Labs ICT
โญ Pro Login

Jinja2 Templates

Dynamic HTML with template syntax.

Jinja2 Templates

Flask uses Jinja2 as its template engine. This lets you separate your Python code from your HTML, making your apps much cleaner. Think of templates as HTML files with special placeholders that Flask fills in for you.

First, you'll use the render_template function. It looks for templates in a folder named "templates" inside your app directory. Here's the basic setup:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/hello/')
def hello(name):
    return render_template('hello.html', name=name)

Now, in your templates/hello.html file, you can use the variable like this:

<!DOCTYPE html>
<html>
<head>
    <title>Hello</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
    <p>Welcome to my Flask tutorial.</p>
</body>
</html>

See those double curly braces? That's how you output variables. It's called variable interpolation. You can pass multiple variables to the template too.

@app.route('/user')
def user():
    name = "Bilal"
    age = 25
    return render_template('profile.html', name=name, age=age)

For logic like loops and conditions, use {% %} tags. Here's a simple loop that lists items:

<ul>
{% for item in items %}
    <li>{{ item }}</li>
{% endfor %}
</ul>

And an if statement to show different content based on conditions:

{% if user.logged_in %}
    <p>Welcome back, {{ user.username }}!</p>
{% else %}
    <p>Please log in.</p>
{% endif %}

One important security feature is auto-escaping. By default, Jinja2 escapes HTML in variables to prevent XSS attacks. If you want to output raw HTML, you need to explicitly mark it as safe. This protects your users from malicious input.

So remember: use render_template to load templates, {{ }} for outputting variables, and {% %} for logic. Keep your templates in the templates folder and you're good to go.

Try it Yourself ->

๐Ÿงช Quick Quiz

What syntax outputs a variable in Jinja2?