How to Use Templates and Static Files in Flask

This blog will teach you how to use templates and static files in Flask, a popular web framework for Python. You will learn how to create and customize your web pages with HTML, CSS, and JavaScript, and how to serve them using Flask.

1. Introduction to Flask

Flask is a popular web framework for Python that allows you to create and run web applications. Flask is based on the concept of microframework, which means it provides a minimal set of features and tools to get started, but it is also flexible and extensible to add more functionality as you need.

In this tutorial, you will learn how to use templates and static files in Flask to make your web application more dynamic and interactive. Templates are files that contain HTML code with placeholders for variables and expressions that are filled in by Flask at runtime. Static files are files that are not processed by Flask, such as images, CSS, and JavaScript files. You will learn how to create and use templates and static files in Flask, how to customize your templates with Jinja2, a powerful template engine, and how to add interactivity with JavaScript.

By the end of this tutorial, you will be able to create a simple web application that displays a list of products and their prices, and allows the user to filter and sort the products by different criteria.

To follow this tutorial, you will need:

  • Python 3 installed on your system. You can download it from here.
  • A text editor or an IDE of your choice. You can use any editor that supports Python, such as VS Code, PyCharm, Sublime Text, etc.
  • A basic understanding of Python and HTML. You don’t need to be an expert, but you should be familiar with the syntax and the basic concepts.

Are you ready to get started? Let’s begin by setting up our Flask project.

2. What are Templates and Static Files?

In this section, you will learn what are templates and static files, and why they are important for web development. Templates and static files are two types of files that you can use in your Flask project to create and serve your web pages.

Templates are files that contain HTML code with placeholders for variables and expressions that are filled in by Flask at runtime. For example, you can use a template to display a list of products that are stored in a database. The template will have a placeholder for the product name, price, and image, and Flask will replace them with the actual values from the database when the web page is requested. This way, you can create dynamic web pages that change according to the data and the user input.

Static files are files that are not processed by Flask, such as images, CSS, and JavaScript files. These files are usually used to add style and interactivity to your web pages. For example, you can use a CSS file to define the color, font, and layout of your web page, and a JavaScript file to add some functionality, such as sorting or filtering the products. Static files are served as they are, without any modification by Flask.

Templates and static files are essential for web development, as they allow you to separate the logic and the presentation of your web application. You can use Flask to handle the logic, such as connecting to the database, querying the data, and processing the user input, and use templates and static files to handle the presentation, such as displaying the data, adding style, and adding interactivity. This way, you can make your web application more modular, maintainable, and reusable.

How do you use templates and static files in Flask? Let’s find out in the next sections.

2.1. Templates

Templates are files that contain HTML code with placeholders for variables and expressions that are filled in by Flask at runtime. Templates allow you to create dynamic web pages that change according to the data and the user input. In this section, you will learn how to create and use templates in Flask.

To use templates in Flask, you need to follow these steps:

  1. Create a folder named templates in your project directory. This is where you will store your template files.
  2. Create a template file with the extension .html in the templates folder. You can name it anything you want, but it is a good practice to use descriptive names that match the purpose of the template. For example, you can name your template file products.html if it displays a list of products.
  3. Write your HTML code in the template file. You can use any HTML tags and attributes that you want, but you need to use a special syntax to insert variables and expressions that will be replaced by Flask. The syntax is {{ variable_or_expression }}. For example, you can use {{ product.name }} to display the name of a product.
  4. Import the render_template function from Flask in your Python file. This function takes the name of the template file as an argument and returns the rendered HTML code.
  5. Use the render_template function in your route function to return the template as a response. You can also pass any variables or data that you want to use in the template as keyword arguments. For example, you can use return render_template(‘products.html’, products=products) to render the products template and pass a list of products as data.

Here is an example of a simple template file that displays a list of products and their prices:

<html>
<head>
    <title>Products</title>
</head>
<body>
    <h1>Products</h1>
    <ul>
        {% for product in products %}
        <li>{{ product.name }} - {{ product.price }}</li>
        {% endfor %}
    </ul>
</body>
</html>

And here is an example of a Python file that uses the template file:

from flask import Flask, render_template

app = Flask(__name__)

products = [
    {'name': 'Apple', 'price': 0.99},
    {'name': 'Banana', 'price': 0.79},
    {'name': 'Orange', 'price': 0.89}
]

@app.route('/')
def index():
    return render_template('products.html', products=products)

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

Templates are a powerful way to create dynamic web pages with Flask. You can use templates to display any kind of data that you want, such as text, images, tables, forms, etc. You can also use templates to create layouts and reuse common elements across your web pages, such as headers, footers, navigation bars, etc.

But how do you customize your templates with logic and control flow? How do you add conditions, loops, filters, macros, and other features to your templates? That’s where Jinja2 comes in. Jinja2 is a template engine that Flask uses to process templates. It provides a rich set of features and syntax that you can use to make your templates more flexible and expressive. In the next section, you will learn how to customize your templates with Jinja2.

2.2. Static Files

Static files are files that are not processed by Flask, such as images, CSS, and JavaScript files. These files are usually used to add style and interactivity to your web pages. In this section, you will learn how to create and use static files in Flask.

To use static files in Flask, you need to follow these steps:

  1. Create a folder named static in your project directory. This is where you will store your static files.
  2. Create static files with the appropriate extensions in the static folder. You can name them anything you want, but it is a good practice to use descriptive names that match the purpose of the file. For example, you can name your CSS file style.css if it defines the style of your web page.
  3. Write your code in the static files. You can use any syntax and features that are supported by the file type. For example, you can use CSS selectors, properties, and values to style your HTML elements in the CSS file.
  4. Link your static files to your template files using the url_for function from Flask. This function takes the name of the endpoint and the filename as arguments and returns the URL of the static file. For example, you can use <link rel=”stylesheet” href=”{{ url_for(‘static’, filename=’style.css’) }}”> to link your CSS file to your HTML file.

Here is an example of a simple static file that defines the style of the web page:

body {
    font-family: Arial, sans-serif;
    background-color: lightblue;
}

h1 {
    color: white;
    text-align: center;
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

li {
    display: inline-block;
    margin: 10px;
    padding: 10px;
    border: 1px solid black;
    background-color: white;
}

And here is an example of a template file that links the static file:

<html>
<head>
    <title>Products</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>Products</h1>
    <ul>
        {% for product in products %}
        <li>{{ product.name }} - {{ product.price }}</li>
        {% endfor %}
    </ul>
</body>
</html>

Static files are essential for web development, as they allow you to add style and interactivity to your web pages. You can use static files to define the color, font, layout, animation, and other aspects of your web page, and to add some functionality, such as sorting, filtering, validating, and other features to your web page. You can also use static files to store and serve images, icons, fonts, and other resources that you want to use in your web application.

But how do you add interactivity with JavaScript? How do you use JavaScript to manipulate the HTML elements, handle the user events, and communicate with the Flask server? That’s what you will learn in the next section.

3. How to Create and Use Templates in Flask

In the previous section, you learned what are templates and static files, and why they are important for web development. In this section, you will learn how to create and use templates in Flask to display dynamic web pages.

To create and use templates in Flask, you need to follow these steps:

  1. Create a folder named templates in your project directory. This is where you will store your template files.
  2. Create a template file with the extension .html in the templates folder. You can name it anything you want, but it is a good practice to use descriptive names that match the purpose of the template. For example, you can name your template file index.html if it displays the home page of your web application.
  3. Write your HTML code in the template file. You can use any HTML tags and attributes that you want, but you need to use a special syntax to insert variables and expressions that will be replaced by Flask at runtime. The syntax is {{ variable_or_expression }}. For example, you can use {{ title }} to display the title of your web page.
  4. Import the render_template function from Flask in your Python file. This function takes the name of the template file as an argument and returns the rendered HTML code.
  5. Use the render_template function in your route function to return the template as a response. You can also pass any variables or data that you want to use in the template as keyword arguments. For example, you can use return render_template(‘index.html’, title=’Home’) to render the index template and pass the title as data.

Here is an example of a simple template file that displays a greeting message and the current date and time:

<html>
<head>
    <title>{{ title }}</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
    <p>The current date and time is {{ datetime }}.</p>
</body>
</html>

And here is an example of a Python file that uses the template file:

from flask import Flask, render_template
from datetime import datetime

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html', title='Home', name='User', datetime=datetime.now())

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

Templates are a powerful way to create dynamic web pages with Flask. You can use templates to display any kind of data that you want, such as text, images, tables, forms, etc. You can also use templates to create layouts and reuse common elements across your web pages, such as headers, footers, navigation bars, etc.

But how do you customize your templates with logic and control flow? How do you add conditions, loops, filters, macros, and other features to your templates? That’s where Jinja2 comes in. Jinja2 is a template engine that Flask uses to process templates. It provides a rich set of features and syntax that you can use to make your templates more flexible and expressive. In the next section, you will learn how to customize your templates with Jinja2.

4. How to Create and Use Static Files in Flask

Static files are files that are not processed by Flask, such as images, CSS, and JavaScript files. These files are usually used to add style and interactivity to your web pages. In this section, you will learn how to create and use static files in Flask.

To use static files in Flask, you need to follow these steps:

  1. Create a folder named static in your project directory. This is where you will store your static files.
  2. Create static files with the appropriate extensions in the static folder. You can name them anything you want, but it is a good practice to use descriptive names that match the purpose of the file. For example, you can name your CSS file style.css if it defines the style of your web page.
  3. Write your code in the static files. You can use any syntax and features that are supported by the file type. For example, you can use CSS selectors, properties, and values to style your HTML elements in the CSS file.
  4. Link your static files to your template files using the url_for function from Flask. This function takes the name of the endpoint and the filename as arguments and returns the URL of the static file. For example, you can use <link rel=”stylesheet” href=”{{ url_for(‘static’, filename=’style.css’) }}”> to link your CSS file to your HTML file.

Here is an example of a simple static file that defines the style of the web page:

body {
    font-family: Arial, sans-serif;
    background-color: lightblue;
}

h1 {
    color: white;
    text-align: center;
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

li {
    display: inline-block;
    margin: 10px;
    padding: 10px;
    border: 1px solid black;
    background-color: white;
}

And here is an example of a template file that links the static file:

<html>
<head>
    <title>Products</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>Products</h1>
    <ul>
        {% for product in products %}
        <li>{{ product.name }} - {{ product.price }}</li>
        {% endfor %}
    </ul>
</body>
</html>

Static files are essential for web development, as they allow you to add style and interactivity to your web pages. You can use static files to define the color, font, layout, animation, and other aspects of your web page, and to add some functionality, such as sorting, filtering, validating, and other features to your web page. You can also use static files to store and serve images, icons, fonts, and other resources that you want to use in your web application.

But how do you add interactivity with JavaScript? How do you use JavaScript to manipulate the HTML elements, handle the user events, and communicate with the Flask server? That’s what you will learn in the next section.

5. How to Customize Your Templates with Jinja2

Jinja2 is a template engine that Flask uses to process templates. It provides a rich set of features and syntax that you can use to make your templates more flexible and expressive. In this section, you will learn how to customize your templates with Jinja2.

To customize your templates with Jinja2, you need to use a special syntax that starts and ends with curly braces and percent signs, like this: {% statement %}. This syntax allows you to add logic and control flow to your templates, such as conditions, loops, filters, macros, and other features. For example, you can use {% if condition %} and {% endif %} to add an if statement to your template, or {% for item in iterable %} and {% endfor %} to add a for loop to your template.

Here are some of the most common features and syntax that you can use to customize your templates with Jinja2:

  • Variables: You can use variables to store and display data in your templates. You can use the same syntax as in Python to assign and access variables, like this: {% set name = ‘User’ %} and {{ name }}. You can also use dot notation to access attributes and methods of objects, like this: {{ product.name }} and {{ product.price }}.
  • Expressions: You can use expressions to perform calculations and operations in your templates. You can use the same syntax as in Python to write expressions, like this: {{ 2 + 2 }} and {{ product.price * 1.1 }}. You can also use comparison and logical operators, like this: {{ product.price > 10 }} and {{ product.name == ‘Apple’ or product.name == ‘Banana’ }}.
  • Filters: You can use filters to modify and format the output of variables and expressions in your templates. You can use the pipe symbol (|) to apply a filter to a variable or expression, like this: {{ name | capitalize }} and {{ product.price | round(2) }}. You can also chain multiple filters, like this: {{ name | lower | replace(‘user’, ‘guest’) }}. Jinja2 provides many built-in filters that you can use, such as capitalize, lower, upper, trim, length, round, format, escape, safe, and more. You can also create your own custom filters if you want.
  • Conditions: You can use conditions to control which part of your template is rendered based on some criteria. You can use the if, elif, and else keywords to create an if statement in your template, like this: {% if product.price > 10 %}, {% elif product.price == 10 %}, and {% else %}. You can also use the in and not in keywords to check if a value is in a list or a dictionary, like this: {% if product.name in [‘Apple’, ‘Banana’, ‘Orange’] %} and {% if product.name not in products.keys() %}.
  • Loops: You can use loops to iterate over a sequence of items in your template. You can use the for and endfor keywords to create a for loop in your template, like this: {% for product in products %} and {% endfor %}. You can also use the break and continue keywords to control the flow of the loop, like this: {% break %} and {% continue %}. You can also access some special variables inside the loop, such as loop.index, loop.first, loop.last, loop.length, and more.
  • Macros: You can use macros to define reusable blocks of code in your template. You can use the macro and endmacro keywords to create a macro in your template, like this: {% macro product_item(product) %} and {% endmacro %}. You can also pass arguments and default values to your macro, like this: {% macro product_item(product, show_price=True) %}. You can then call your macro anywhere in your template, like this: {{ product_item(product) }} and {{ product_item(product, show_price=False) }}. Macros are useful for creating reusable components and avoiding code duplication in your template.

Here is an example of a template file that uses some of the features and syntax of Jinja2 to customize the web page:

<html>
<head>
    <title>{{ title }}</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>Hello, {{ name | capitalize }}!</h1>
    <p>The current date and time is {{ datetime | format('%Y-%m-%d %H:%M:%S') }}.</p>
    <h2>Products</h2>
    <ul>
        {% for product in products %}
        <li>{{ product_item(product) }}</li>
        {% endfor %}
    </ul>
    {% macro product_item(product, show_price=True) %}
    <div class="product">
        <img src="{{ url_for('static', filename=product.image) }}" alt="{{ product.name }}">
        <h3>{{ product.name }}</h3>
        {% if show_price %}
        <p>Price: {{ product.price | round(2) }}</p>
        {% endif %}
    </div>
    {% endmacro %}
</body>
</html>

And here is an example of a Python file that uses the template file:

from flask import Flask, render_template
from datetime import datetime

app = Flask(__name__)

products = [
    {'name': 'Apple', 'price': 0.99, 'image': 'apple.png'},
    {'name': 'Banana', 'price': 0.79, 'image': 'banana.png'},
    {'name': 'Orange', 'price': 0.89, 'image': 'orange.png'}
]

@app.route('/')
def index():
    return render_template('index.html', title='Home', name='User', datetime=datetime.now(), products=products)

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

Jinja2 is a powerful template engine that allows you to customize your templates with logic and control flow. You can use Jinja2 to add conditions, loops, filters, macros, and other features to your templates, making them more flexible and expressive. You can also use Jinja2 to create layouts and inheritance, which are advanced features that you can use to create a base template and extend it to other templates, avoiding code duplication and creating a consistent look and feel for your web application. You can learn more about Jinja2 and its features and syntax from the official documentation.

But how do you add interactivity with JavaScript? How do you use JavaScript to manipulate the HTML elements, handle the user events, and communicate with the Flask server? That’s what you will learn in the next section.

6. How to Add Interactivity with JavaScript

JavaScript is a scripting language that runs in the browser and allows you to add dynamic and interactive features to your web pages. For example, you can use JavaScript to manipulate the HTML elements, respond to user events, validate user input, communicate with the server, and more.

In this section, you will learn how to add interactivity to your web application with JavaScript. You will use JavaScript to implement some functionality that allows the user to filter and sort the products by different criteria, such as price, category, and rating. You will also use JavaScript to update the web page without reloading it, using a technique called Ajax.

To follow this section, you will need:

  • A basic understanding of JavaScript and its syntax. You don’t need to be an expert, but you should be familiar with the basic concepts, such as variables, functions, loops, arrays, objects, events, etc.
  • A text editor or an IDE of your choice. You can use any editor that supports JavaScript, such as VS Code, Sublime Text, etc.
  • A web browser that supports JavaScript, such as Chrome, Firefox, Safari, etc.

Are you ready to add some interactivity to your web application? Let’s begin by creating a JavaScript file and linking it to our template.

7. Conclusion and Resources

In this tutorial, you have learned how to use templates and static files in Flask to create a dynamic and interactive web application. You have learned how to:

  • Create and use templates in Flask to display data from a database.
  • Create and use static files in Flask to add style and functionality to your web pages.
  • Customize your templates with Jinja2, a powerful template engine that allows you to use variables, expressions, filters, loops, and more.
  • Add interactivity to your web application with JavaScript, a scripting language that runs in the browser and allows you to manipulate the HTML elements, respond to user events, validate user input, communicate with the server, and more.

You have also created a simple web application that displays a list of products and their prices, and allows the user to filter and sort the products by different criteria.

By using templates and static files in Flask, you have made your web application more modular, maintainable, and reusable. You have also separated the logic and the presentation of your web application, making it easier to debug and test.

Now that you have learned how to use templates and static files in Flask, you can apply these skills to create your own web applications with Flask. You can also explore more features and functionalities of Flask, such as sessions, cookies, forms, authentication, etc.

If you want to learn more about Flask, templates, static files, Jinja2, or JavaScript, here are some useful resources:

  • Flask Documentation: The official documentation of Flask, with tutorials, guides, and API reference.
  • Jinja Documentation: The official documentation of Jinja, with tutorials, guides, and API reference.
  • JavaScript: A series of articles and tutorials on JavaScript from Mozilla Developer Network.
  • HTML Tutorial: A comprehensive tutorial on HTML from W3Schools.
  • CSS Tutorial: A comprehensive tutorial on CSS from W3Schools.

We hope you enjoyed this tutorial and learned something new. Thank you for reading and happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *