0
0
Flaskframework~5 mins

Why template engines matter in Flask

Choose your learning style9 modes available
Introduction

Template engines help you create web pages by mixing code and design easily. They keep your website organized and make it simple to update content.

You want to show dynamic content like user names or lists on a webpage.
You need to separate the look of your site from the data it shows.
You want to reuse parts of your webpage like headers or footers on many pages.
You want to avoid writing HTML inside your Python code directly.
You want to make your website easier to maintain and update.
Syntax
Flask
{% block content %}
  <h1>Hello, {{ user_name }}!</h1>
{% endblock %}
Use double curly braces {{ }} to insert variables into HTML.
Use {% %} for control statements like loops or conditions.
Examples
Insert a variable called user_name into the HTML.
Flask
<h1>Welcome, {{ user_name }}!</h1>
Show different messages based on a condition.
Flask
{% if user_is_logged_in %}
  <p>Welcome back!</p>
{% else %}
  <p>Please log in.</p>
{% endif %}
Loop through a list and display each item.
Flask
{% for item in items %}
  <li>{{ item }}</li>
{% endfor %}
Sample Program

This Flask app uses a template string to greet the user by name. The template engine replaces {{ user_name }} with 'Alice' when rendering the page.

Flask
from flask import Flask, render_template_string

app = Flask(__name__)

@app.route('/')
def home():
    user_name = 'Alice'
    template = '''
    <html>
      <head><title>Welcome</title></head>
      <body>
        <h1>Hello, {{ user_name }}!</h1>
      </body>
    </html>
    '''
    return render_template_string(template, user_name=user_name)

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Template engines keep your Python code clean by separating HTML from logic.

They help prevent security issues by escaping harmful input automatically.

Flask uses Jinja2 as its default template engine, which is powerful and easy to learn.

Summary

Template engines mix data and design to build web pages easily.

They help keep your code organized and your site easy to update.

Flask's template engine uses simple tags to insert variables and control flow.