Introduction to Jinja2 template engine
What is Jinja2?
Jinja2 is a template engine for Python. A template engine is a tool that allows developers to render data in different formats. Jinja2 is highly flexible and easy to use, making it a popular choice for developers seeking to implement dynamic web pages.
Why Use Jinja2 in Flask?
Jinja2 is the default template engine in Flask. This means that Flask is pre-configured to use Jinja2. Also, Flask provides a bridge between Python code and HTML, allowing for seamless integration of Python data in HTML templates.
Jinja2 Basics
Variables
Variables in Jinja2 are denoted by double curly braces {{ }}
. For example, if you have a variable name
in your Python code, you can include it in your HTML template as {{ name }}
.
Hello, {{ name }}!
Control Structures
Control structures in Jinja2 include for loops and if-else statements. They are denoted by {% %}
.
For loop example:
<ul>
{% for user in users %}
<li>{{ user }}</li>
{% endfor %}
</ul>
If-else statement example:
{% if user.is_admin %}
<p>Welcome, admin!</p>
{% else %}
<p>Welcome, {{ user.name }}!</p>
{% endif %}
Filters
Filters in Jinja2 are used to transform the output. They are denoted by a pipe |
.
Example of using a filter to convert a string to uppercase:
{{ name | upper }}
How to Use Jinja2 in Flask
To use Jinja2 in Flask, you need to create an HTML file in the templates
directory of your Flask project. You can then render this template in your Flask view function using the render_template()
function.
Here's an example:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html', name='John')
In this example, render_template()
takes the name of the template file and any variables you want to pass to the template. These variables can then be accessed in the template using Jinja2 syntax.
Conclusion
Jinja2 is a versatile and powerful tool that makes it easy to create dynamic web pages in Flask. It provides a bridge between Python and HTML, allowing you to seamlessly integrate Python data in your HTML templates. Whether you're developing a small personal project or a large-scale web application, Jinja2 can make your development process more efficient and enjoyable.