Templates in Flask

Boost Your Career with In-demand Skills - Start Now!

Web development has come a long way over the years, and with the rise of Python as a popular programming language, there are now numerous frameworks available for building web applications. One such framework is Flask, a micro web framework that provides a lightweight and flexible way to develop web applications in Python. One of the key features of Flask is its built-in support for templates, which allow developers to create dynamic web pages with ease. In this article, we will explore Flask templates and how they can be used to build powerful web applications.

What are Flask Templates?

In Flask, a template is a separate file that contains HTML code mixed with Python code, known as template tags. These template tags allow you to dynamically render data in your HTML views. Flask uses a templating engine called Jinja2, which is a powerful and flexible templating engine that provides many advanced features for building dynamic web pages. Flask templates allow you to separate the logic and presentation of your web application, making it easier to manage and maintain your code.

Creating Flask Templates

Creating a Flask template is simple. You can create a templates folder in your Flask application directory, and then create separate HTML files inside that folder for each view or page of your web application. Flask will automatically look for templates in the templates folder and render them when a request is made to the corresponding route.

Here’s an example of how you can create a simple Flask template:

1. Create a templates folder in your Flask application directory.

2. Inside the templates folder, create a file called index.html, which will be the template for your home page.

3. In the index.html file, you can write regular HTML code mixed with template tags. For example:

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

Output –

Hello, Pythongeeks!
Welcome to my Flask app.

In the above example, {{ name }} is a template tag that represents a placeholder for a variable that will be passed to the template when it is rendered.

Rendering Flask Templates

Once you have created a Flask template, you can use the render_template function provided by Flask to render the template and generate the HTML output. The render_template function takes the name of the template file as an argument and returns the rendered HTML as a response that can be sent back to the client.

Here’s an example of how you can render a Flask template in a view function:

from flask import Flask, render_template


app = Flask(__name__)


@app.route('/')
def pythongeeks_index():
   name = 'John' # Variable to be passed to the template
   return render_template('index.html', name=name)

In the above example, the render_template function is used to render the index.html template and pass the value of the name variable to the template. The template will then render the value of name in the placeholder {{ name }} and generate the HTML output that will be sent as a response to the client.

Template Inheritance

One of the powerful features of Flask templates is template inheritance. It allows you to define a base template with common elements such as header, footer, and navigation bar, and then extend it in child templates with additional content. This makes it easy to create consistent and reusable layouts for your web application.

To use template inheritance in Flask, you can define a base template that includes the common elements. Then, use the {% extends %} template tag in child templates to inherit from the base template. Child templates can then override or add new blocks of content using the {% block %} template tag.

Here’s an example of how you can use template inheritance in Flask:

1. Create a base template, let’s call it base.html, that includes common elements such as the header, footer, and navigation bar:

<!DOCTYPE html>
<html>
 <head>
   <title>My Pythongeeks Flask App</title>
   <!-- Include common CSS and JavaScript files -->
 </head>
 <body>
   <header>
     <!-- Header content goes here -->
   </header>
   <nav>
     <!-- Navigation bar content goes here -->
   </nav>
   <main>
     {% block content %}
     <!-- Content for child templates goes here -->
     {% endblock %}
   </main>
   <footer>
     <!-- Footer content goes here -->
   </footer>
 </body>
</html>

In the above example, {% block content %} is a template tag that defines a block of content that can be overridden in child templates.

2. Create a child template, let’s call it index.html, that extends the base.html template and provides content for the overridden block:

{% extends 'base.html' %} {% block content %}
<h1>Hello, {{ name }}!</h1>
<p>Welcome to my pythongeeks Flask app.</p>
{% endblock %}

In the above example, {% extends ‘base.html’ %} is a template tag that indicates that the index.html template extends the base.html template. The content inside {% block content %} will override the corresponding block in the base template, allowing you to provide custom content for each child template.

Template Control Structures

Jinja2, the templating engine used by Flask, provides powerful control structures that allow you to add logic and perform conditional rendering in your templates. Some of the common control structures used in Flask templates are:

1. {% if %}…{% endif %}: Allows you to add conditional statements in your template. For example:

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

Output –

Please log in.

2. {% for %}…{% endfor %}: Allows you to loop over a list or dictionary in your template. For example:

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

3. {% macro %}…{% endmacro %}: Allows you to define reusable macros in your template. For example:

{% macro render_user(user) %}
<p>Pythongeeks_Name: {{ user.name }}</p>
<p>Pythongeeks_Email: {{ user.email }}</p>
{% endmacro %}


<!-- Usage -->
{{ render_user(user) }}

These control structures provide a powerful way to add dynamic behavior to your templates and create dynamic web pages.

Referring Static files in HTML

In a Flask application, you can refer to static files such as CSS, JavaScript, and images in your HTML templates using a special URL pattern. Here’s a short note on how to refer to static files in HTML templates in Flask:

1. Create a “static” folder in your Flask project directory:

You need to create a folder named “static” at the same level as your Flask app file (usually named “app.py”) or in any other location that Flask can find using the static_folder parameter when initializing the Flask app.

2. Place static files in the “static” folder:

Put your static files such as CSS, JavaScript, and images in the “static” folder. You can organize them in subdirectories within the “static” folder if desired.

3. Use the url_for function to generate URLs for static files in HTML templates:

In your HTML templates, use the url_for function provided by Flask to generate URLs for static files. The url_for function takes the name of the static file as an argument and returns a URL that points to that file. For example, to refer to a CSS file named “styles.css” in your HTML template, you can use the following code:

<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">

4. Update the “static” URL pattern in Flask app:

In your Flask app, you need to specify the “static” URL pattern so that Flask knows how to handle requests for static files. You can do this using the static_url_path parameter when initializing the Flask app, like this:

app = Flask(__name__, static_url_path='/static'

5. Use the generated URL in your HTML templates:

Now you can use the generated URL from the url_for function in your HTML templates to refer to static files, and Flask will automatically serve the static files when the corresponding URL is requested.

By following these steps, you can easily refer to static files in HTML templates in your Flask application, allowing you to serve CSS, JavaScript, and image files to enhance the appearance and functionality of your web pages.

Delimiters in Flask Templates

Delimiters in Flask templates refer to the symbols or characters used to indicate template expressions and statements in the template files. Flask uses a templating engine called Jinja2, which allows developers to create dynamic HTML pages by embedding Python code within HTML templates.

In Jinja2, there are two main types of delimiters:

1. Expression Delimiters:

Expression delimiters are used to embed Python expressions within HTML templates. The default expression delimiters in Jinja2 are {{ and }}. For example, {{ variable_name }} will output the value of the variable_name in the rendered HTML.

2. Statement Delimiters:

Statement delimiters are used to embed Python statements or control flow statements within HTML templates. The default statement delimiters in Jinja2 are {% and %}. For example, {% if condition %}…{% endif %} allows you to add conditional statements in your template.

It’s important to note that the delimiters in Jinja2 can be customized using the ‘block_start_string, block_end_string’, ‘variable_start_string’, ‘variable_end_string’, ‘comment_start_string’, and ‘comment_end_string’ configuration options in Flask. This allows developers to use different delimiters if needed.

Delimiters in Flask templates are essential for creating dynamic web pages by embedding Python code within HTML templates, making it easy to generate dynamic content based on data and logic in your Flask application. Proper usage of delimiters is crucial for writing clean and maintainable Flask templates.

Conclusion

Flask templates are a powerful tool for building dynamic web pages in Python. With the built-in support for Jinja2 templating engine, Flask allows you to easily separate the logic and presentation of your web application, making it more maintainable and scalable. Template inheritance, along with control structures, provide additional flexibility and power to your templates, allowing you to create complex web applications with ease.

In this article, we explored the basics of Flask templates, including how to create templates, render them in views, and use template inheritance and control structures. By leveraging the power of Flask templates, you can create dynamic web applications that provide a seamless and interactive user experience. So, go ahead and give Flask templates a try in your next web development project and unlock the full potential of Python for web development!

Did we exceed your expectations?
If Yes, share your valuable feedback on Google | Facebook


PythonGeeks Team

PythonGeeks Team is dedicated to creating beginner-friendly and advanced tutorials on Python programming, AI, ML, Data Science and more. From web development to machine learning, we help learners build strong foundations and excel in their Python journey.

Leave a Reply

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