A Simple Configuration Generator Using Jinja2 and Python

Jinja is a templating engine available in Python programming language. Jinja2 is the latest release of this templating engine. The terms Jinja and Jinja2 are often used interchangeably. It is a text-based template language and thus can be used to generate any source code or markup. A Jinja template file is simply a text file that contains Jinja language constructs – variables, conditional statements, loops, etc. The Jinja engine takes the template file and data variables as input. The Jinja engine processes these constructs, expands variables to their values and render a text output that is free of any Jinja markup.

For example, here the variable “template” represents a Jinja template. Generally, template is read from a file, but here it is directly given for simplicity. Jinja variables inside {{}} brackets are replaced with their values in the output. The Python dictionary “data” contains the values for the variables referenced inside the template.

from jinja2 import Template

template = """
Hello {{planet}}.
My name is {{name}}.
"""

data = {"planet": "Earth", "name": "Rashid"}

t = Template(template)
r = t.render(data)

print(r)

The above code renders this output.

Hello Earth.
My name is Rashid.

Read More