Flask Tutorial: Templates

Flask, a Python-based micro web framework, stands out for its simplicity and flexibility. It's renowned for its support of templates, enabling developers to effortlessly render dynamic HTML content, enhancing user experiences. This tutorial will guide you through the basics of using templates in Flask with a step-by-step example.

 

 

Flask Tutorials

 

 

Before you begin, ensure you have the following installed:

  • Python 3.x
  • Flask 

 

To install Flask, use pip:



pip install flask



Step 1: Setting Up Your Project 

Create a new directory for your project and navigate into it:



mkdir flask_template_tutorial
cd flask_template_tutorial



Inside this directory, create a virtual environment to manage your dependencies:

 


python -m venv venv
source venv/bin/activate  # On Windows use `venv\Scripts\activate`



Next, install Flask in your virtual environment:



pip install flask


In case, you don't know the process, you can create it manually. Like right-click on the project folder and create the folder and name it 'templates'.

 

Read also:

 


Step 2: Creating the Basic Flask Application



Create a new file named `app.py` and add the following code to set up a basic Flask application:




from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, Flask!"

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


Run your application to ensure it's working:



python app.py


Visit `http://127.0.0.1:5000/` in your web browser. You should see "Hello, Flask!".

 

flask tutorial templates

 

flask tutorial templates

 


Step 3: Setting Up Templates



Flask uses the Jinja2 template engine by default. To use templates, you need to create a `templates` directory in your project root. This is where Flask looks for HTML files.



Create the `templates` directory:




mkdir templates


Inside the `templates` directory, create an HTML file named `home.html` with the following content:




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask Template Tutorial</title>
</head>
<body>
    <h1>{{ title }}</h1>
    <p>Welcome to Flask Templates!</p>
</body>
</html>



Step 4: Rendering Templates



Modify `app.py` to render this template instead of returning a plain string:




from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html', title="Hello, Flask!")

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


In this code, `render_template('home.html', title="Hello, Flask!")` tells Flask to render the `home.html` template and pass the variable `title` to it.



Run your application again:



python app.py


When you visit `http://127.0.0.1:5000/`, you should see "Hello, Flask!" displayed as a heading.



Step 5: Adding More Dynamic Content



Let's add more dynamic content to our template. Modify `home.html` to include a list of items:



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask Template Tutorial</title>
</head>
<body>
    <h1>{{ title }}</h1>
    <p>Welcome to Flask Templates!</p>
    <ul>
        {% for item in items %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
</body>
</html>


Update `app.py` to pass a list of items to the template:



from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    items = ["Item 1", "Item 2", "Item 3"]
    return render_template('home.html', title="Hello, Flask!", items=items)

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


Run your application again:




python app.py


When you visit `http://127.0.0.1:5000/`, you should see a list of items rendered below the welcome message.

 

flask tutorial templates

 



Step 6: Creating a Base Template



In larger applications, you'll want to reuse common HTML structures like headers and footers. Flask allows you to create a base template that other templates can extend.



Create a new file named `base.html` in the `templates` directory:




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}Flask Application{% endblock %}</title>
</head>
<body>
    <header>
        <h1>My Flask App</h1>
    </header>
    <main>
        {% block content %}{% endblock %}
    </main>
    <footer>
        <p>&copy; 2024 My Flask App</p>
    </footer>
</body>
</html>


Modify `home.html` to extend `base.html`:




{% extends "base.html" %}

{% block title %}{{ title }}{% endblock %}

{% block content %}
    <p>Welcome to Flask Templates!</p>
    <ul>
        {% for item in items %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
{% endblock %}


With this setup, `home.html` now inherits the structure from `base.html` and defines the `title` and `content` blocks.



Step 7: Adding More Routes and Templates



Add another route and template to see how easy it is to expand your application:



Create a new template named `about.html`:



{% extends "base.html" %}

{% block title %}About Us{% endblock %}

{% block content %}
    <p>This is the about page.</p>
{% endblock %}


Update `app.py` to include a new route:



from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    items = ["Item 1", "Item 2", "Item 3"]
    return render_template('home.html', title="Hello, Flask!", items=items)

@app.route('/about')
def about():
    return render_template('about.html')

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


Run your application again:



python app.py


Visit `http://127.0.0.1:5000/about`, and you'll see the "About Us" page with its own content. 

 

Key Takeaways


Templates are essential in Flask for rendering dynamic HTML content. They enable separation of logic and presentation, making code more maintainable.


  • Templates Directory: Store your HTML files in the `templates` directory.
  • Jinja2 Engine: Flask uses the Jinja2 templating engine, which allows for variable substitution and control structures.
  • Render Templates: Use `render_template()` to render HTML templates and pass data to them.
  • Template Inheritance: Create a base template to reuse common HTML structures across different pages.


Important Points


  • Set up a virtual environment :  to manage dependencies and keep your project isolated.
  • Use `render_template : to render HTML files and pass dynamic content to them.
  • Template Variables: Pass variables to templates for dynamic content using the `render_template` function.
  • Control Structures: Use Jinja2 syntax for loops and conditionals within templates.
  • Extend Base Templates: Utilize template inheritance to maintain a consistent layout and avoid repetition.


Conclusion


In this tutorial, you've learned how to set up a basic Flask application and render dynamic content using templates. You now know how to:

  • Create and render templates 
  • Pass variables to templates 
  • Use template inheritance to create reusable layouts 
  • Add multiple routes and templates to your Flask application 

 Flask templates make it easy to create dynamic and maintainable web applications.

Previous Post Next Post