Templating’ engine is an engine that can manipulate your HTML code from the server-side by using the server-side code. A template engine is quite popular in frameworks. In the template engine, we can replace variables with the values sent from the source and use it as an HTML file.
Jinja is a popular template engine of the python programming language. Jinja is basically used by Flask as the templating engine.
To install jinja –
pip install Jinja2
Basic Template Example of Jinja –
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Python Webpage</title>
</head>
<body>
<ul id=”users">
{% for user in users %}
<li><a href="{{ user.website }}">{{ user.name }}</a></li>
{% endfor %}
</ul>
<h1>Important Info - </h1>
{{ info }}
{# a comment #}
</body>
</html>
There are a few kinds of delimiters. The default Jinja delimiters are configured as follows:
-
{% … %} is used for Statements
E.g. {% set text = ‘Hello Word’ %} -
{{ … }} for Expressions to print the value.
E.g. {{text}} -
{# … #} are used for Comments which are not needed in template output
E.g. {# This is an example of jinja template #} -
# … ## for Line Statements
# for item in seq:
…
# endfor
Example – How to input values from python to jinja template –
—————————— jinja_generate_html.py —————————————-
from jinja2 import Environment, FileSystemLoader
import os
root = os.path.dirname(os.path.abspath(__file__)) #get the absolute path of the python file.
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('template.html') #Get the template
filename = os.path.join(root, 'output', 'index.html') #adding path in root
with open(filename, 'w') as fh: #open file output/index.html in write mode
#render the template i.e. replace variable with the passing values and write it to the index.html with the updated values
fh.write(template.render(
my_string = "Hello User",
my_list = ["JAVA", "Python"],
))
———————————-Template.html —————————————-
<!DOCTYPE html>
<html>
<head>
<title>Jinja2 Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="container">
<p>Title : {{my_string}}</p>
<p>Value from the list: {{my_list[3]}}</p>
<p>Loop through the list:</p>
<ul>
{% for n in my_list %}
<li>{{n}}</li>
{% endfor %}
</ul>
</div>
</body>
</html>
If you have skills in PHP programming and you want to enhance your career in this field, a PHP certification from StudySection can help you reach your desired goals. Both beginner level and expert level PHP certification exams are offered by StudySection along with other programming certification exams.