Using Jinja2 with Templates
Introduction
Jinja2 is a powerful templating engine for Python. It helps developers create dynamic web applications by separating the HTML structure from the data. In this tutorial, you will learn how to use Jinja2 with templates to create dynamic content.
Setting Up Jinja2
First, you need to install Jinja2. You can use pip to install it:
pip install jinja2
Once installed, you can start using Jinja2 in your Python projects.
Creating a Template
Create a new file called template.html
with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Jinja2 Template</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>
This template contains a placeholder {{ name }}
which will be replaced with actual data.
Rendering the Template
Next, create a Python script to render the template. Create a file called app.py
with the following content:
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('template.html')
output = template.render(name='CrewAI')
with open('output.html', 'w') as f:
f.write(output)
This script uses Jinja2 to load the template and render it with the name "CrewAI". The rendered content is then written to an output file called output.html
.
Viewing the Output
After running the Python script, open the output.html
file in your web browser. You should see the following output:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Jinja2 Template</title>
</head>
<body>
<h1>Hello, CrewAI!</h1>
</body>
</html>
The placeholder {{ name }}
has been replaced with "CrewAI".
Using Control Structures
Jinja2 supports various control structures such as loops and conditionals. Update the template.html
file to include a loop:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Jinja2 Template</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
Update the app.py
script to pass a list of items to the template:
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('template.html')
output = template.render(name='CrewAI', items=['Item 1', 'Item 2', 'Item 3'])
with open('output.html', 'w') as f:
f.write(output)
This will render a list of items in the output HTML file.
Conclusion
In this tutorial, you have learned how to use Jinja2 with templates to create dynamic HTML content. You have seen how to set up Jinja2, create and render templates, and use control structures like loops. Jinja2 is a versatile tool that can greatly enhance your web development projects by separating data from presentation.