Template engines are software components that allow us to make text templates with a few places left for customization. This saves us time and effort when we need to make a lot of clones of a generic text with minor changes in each clone. While template engines can help us streamline our workflow for day-to-day tasks, they also make application and web development easier and quicker.
Note: To read up more about template engines, you may read this Answer on Educative.
To make text clones in Python, we use a library known as Jinja2, which provides template engine functionality for all sorts of text, including LaTeX and HTML. Each clone can be an exact copy of each other or may vary a bit depending on our requirements.
Jinja2 is extensible, expressive, and fast. Changes in the template are possible using special placeholders that resemble Python syntax.
Note: If you are unfamiliar with Jinja2, you may want to read this Answer on Educative.
Jinja2 supports extensions, which are custom components that enhance the functionality of the Jinja2 templating engine. These extensions enable additional functionalities that may not be available by default. Extensions are particularly useful when we need to customize Jinja2 to meet the specific requirements of an application.
Jinja2 provides the following built-in extensions that boost its functionality significantly.
In this example, the first code demonstrates the use of a for
loop with Jinja2, while the second code demonstrates the use of a control statement within the for
loop.
for
loop in Jinja2The following code demonstrates the implementation of a for
loop in a Jinja2 template.
from jinja2 import Environment# Initialize a Jinja2 environmentenv = Environment()# Define the template stringtemplate_string = """Jinja2 for loop example{% for name in friends %}Hello {{ name }}{% endfor %}"""# Create a template from the template stringtemplate = env.from_string(template_string)# Data to replace "name" in templatefriends = ["Bilal", "Dian", "Zara", "Muizz", "Hassan", "Aymen"]# Render the template with the name listoutput = template.render(friends = friends)# Output the rendered fileprint(output)
Line 4: Create a Jinja2 environment with default values using the empty parenthesis.
Lines 7–13: Provide the template in the string format. The for
loops in Jinja2 require an end statement, as written in line 12. The loop in the template goes over the friends
list and creates a clone with a new value each time. The variable inside the {{
will be replaced with the value of the variable in each iteration.
Line 16: Create a template out of the provided template text.
Line 19: Create a list to provide to the for
loop in the template. A new clone will be made for each value in the list.
Line 22: The render
attribute of the Jinja2 template runs the for
loop inside the template and creates a new clone with each iteration. All the clones are stored inside the output
variable as a Python string.
for
loop with controls in Jinja2The following code demonstrates the loop controls in Jinja2 templates.
from jinja2 import Environment, FileSystemLoaderfrom jinja2.ext import loopcontrols# Initialize the Jinja2 environment with loopcontrols extensionenv = Environment(loader=FileSystemLoader("templates"), extensions=[loopcontrols])# Define the template stringtemplate_string = """Jinja2 for loop with break example{% for name in friends %}Hello {{ name }}{% if name == "Muizz" %}Link broken{% break %}{% endif %}{% endfor %}"""# Create a template from the template stringtemplate = env.from_string(template_string)# Data to replace "name" in templatefriends = ["Bilal", "Dian", "Zara", "Muizz", "Hassan", "Aymen"]# Render the template with the name listoutput = template.render(friends = friends)# Print the rendered outputprint(output)
Line 5: Alter the default environment with an extension, loopcontrol
.
Line 13–16: Implement an if
statement inside the template. Just like the for
loop, the if
statement also needs an ending statement. Inside the conditional block, we have the break
statement that stops the loop from iterating further.
Jinja2 is a Python library known for its extensibility, expressiveness, and speed. It also offers extensions like loop controls, translation, expression statements, whitespace trimming, and debugging. With some practice, it can be a powerful tool for the user.
Free Resources