Author - StudySection Post Views - 47 views
jinja template engine

Jinja – Web Template Engine in Python

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">
<title>My Python Webpage</title>
<ul id=”users">
{% for user in users %}
<li><a href="{{ }}">{{ }}</a></li>
{% endfor %}

<h1>Important Info - </h1>
{{ info }}

{# a comment #}

There are a few kinds of delimiters. The default Jinja delimiters are configured as follows:

  1. {% … %} is used for Statements
    E.g. {% set text = ‘Hello Word’ %}
  2. {{ … }} for Expressions to print the value.
    E.g. {{text}}
  3. {# … #} are used for Comments which are not needed in template output
    E.g. {# This is an example of jinja template #}
  4. # … ## for Line Statements
    # for item in seq:

    # endfor

Example – How to input values from python to jinja template –

—————————— —————————————-

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
my_string = "Hello User",
my_list = ["JAVA", "Python"],

———————————-Template.html —————————————-

<!DOCTYPE html>
<title>Jinja2 Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<div class="container">
<p>Title : {{my_string}}</p>
<p>Value from the list: {{my_list[3]}}</p>
<p>Loop through the list:</p>
{% for n in my_list %}
{% endfor %}

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.

Leave a Reply

Your email address will not be published. Required fields are marked *