Elevate Your Flask App with Bootstrap and HTML Inheritance: Flask Tutorial #4, Lecture 4 in Python

Posted by

In this tutorial, we will be focusing on how to boost your Flask app by integrating Bootstrap and using HTML inheritance. By using these techniques, you can enhance the look and feel of your Flask app and make it more user-friendly and visually appealing.

  1. Setting up Bootstrap in your Flask app:
    Bootstrap is a popular CSS framework that allows you to easily create responsive and mobile-friendly websites. To use Bootstrap in your Flask app, you first need to include the Bootstrap CSS and JavaScript files in your project. You can either download the files from the official Bootstrap website or use a CDN link.

To include Bootstrap in your Flask app, add the following code to your base HTML template:

<!DOCTYPE html>
<html>
<head>
    <title>My Flask App</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
  1. Creating a base HTML template with HTML inheritance:
    HTML inheritance allows you to create a base HTML template that contains common elements (such as headers, footers, navigation menus, etc.) and then extend it in other templates to avoid repetitive code.

To create a base HTML template in Flask, create a new file called base.html and add the following code:

{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-md-6">
        <h1>Welcome to my Flask App!</h1>
    </div>
</div>
{% endblock %}
  1. Creating a new HTML template with Bootstrap styles:
    To create a new HTML template that uses Bootstrap styles, create a new file called index.html and add the following code:
{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-md-6">
        <h1>Welcome to my Flask App!</h1>
        <p>This is a simple Flask app with Bootstrap integration.</p>
        <button class="btn btn-primary">Click me!</button>
    </div>
</div>
{% endblock %}
  1. Running your Flask app:
    To run your Flask app with the newly integrated Bootstrap styles, start the Flask development server by running the following command in your terminal:
python app.py

Open a web browser and navigate to http://localhost:5000 to see your Flask app in action with Bootstrap styles.

In this tutorial, we have learned how to boost your Flask app by integrating Bootstrap and using HTML inheritance. By following these steps, you can create visually appealing and user-friendly Flask apps that stand out from the crowd. Feel free to experiment with different Bootstrap components and styles to customize your Flask app according to your preferences. Happy coding!