Jinja 2 is a powerful Python template that helps us create dynamic content (i.e.) periodically updated data. For example, data like input from users, some values to be entered, etc. come under dynamic data.
You need not type any manual data like HTML for each dynamic content. It is widely used in frameworks like Flask and Django. Flask is a lightweight API framework and Django is used for larger level projects.
1. Open your terminal and type:
pip install jinja2
This way, we will install Jinja 2. A thing to make a note of is to have extensions like .j2 and .html for all your Jinja files.
Eg:
<h1>Hi, {{ name }}!</h1>
<p>Welcome</p>
The double curly braces indicate where the dynamic content should go. Let us have this file named template.j2.
2. Now, let me render the template.
from jinja2 import Environment, FileSystemLoader
# Create a Jinja2 environment with the template directory
env = Environment(loader=FileSystemLoader(“.”))
# Load the template
template = env.get_template(“template.j2”)
# Define variables
context = {“name”: “Aamir”}
# Render the template with variables
output = template.render(context)
print(output)
The output will be
<h1>Hi, Aamir!</h1>
<p>Welcome</p>
3. The context dictionary in the example above holds the data you want to insert into the template. You can pass any number of variables in the dictionary.
4. Conditional statements like if, else and endif are the statements you can use.
Eg:
{% if age >= 18 %}
<p>You are an adult.</p>
{% else %}
<p>You are a minor.</p>
{% endif %}
5. We can loop through lists. I mean you can display a list of items.
<ul>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</ul>
Assuming fruits is a list [“apple”, “banana”, “orange”], the output will be:
<ul>
<li>apple</li>
<li>banana</li>
<li>orange</li>
</ul>
6. Applying filters
Filters allow you to modify variables before displaying them. For example, you can format a date using the date filter:
<p>Today’s date: {{ today | date(“YYYY-MM-DD”) }}</p>
7. You can include other templates using the {% include ‘template_name’ %} directive.
8. Jinja2 supports template inheritance, allowing you to create base templates with common elements and extend them in child templates.
So, that’s it for the day! Thanks for your time in reading my article. Tell me your feedback or views in the comments section.
Check out this link to know more about me
Get my books, podcasts, placement preparation, etc.
https://linktr.ee/aamirp
Get my Podcasts on Spotify
https://lnkd.in/gG7km8G5
Catch me on Medium
https://lnkd.in/gi-mAPxH
Udemy (Python Course)
https://lnkd.in/grkbfz_N