DEV Community

Cover image for jinja
bluepaperbirds
bluepaperbirds

Posted on

jinja

You can build web applications in the Python programming language with the Flask framework (what is Flask).

When creating the user interface, you want to use variables from your Python code. You can do that with a template engine. Templates are what the end user see in their web browser.

That means that in Python code you have some output (variables), which are then passed to the template for that URL.

template engine

What is Jinja

Jinja is the template engine used by Flask. Every Jinja file is an HTML file with a minor twist.

Jinja templates use {% ... %} for expressions and logic, for outputting results while {{ ... }} is used. That means that the html is replace with values from your Python code.

So your jinja html file could look something like this:

<head>
    <title>Jinja example</title>
</head>
<body>
    <h1>Chapter {{chapter}}</h1>
    <p>String a is {{a}}</p>
    <p>String b is {{b}}</p>
</body>

If you don't know Python, you should learn Python before trying Flask or playing with jinja.

Quick examples

You can test the jinja2 template engine in the Python shell. First install Flask using the Python package manager pip. Then install it with

pip install flask

Open up your Python shell to try out jinja:

>>> from jinja2 import Template
>>> x = 3
>>> t = Template("Variable x is {{ x }}")
>>> t.render(x=x)
'Variable x is 3'
>>>
>>> t = Template("Lucky numbers {% for i in range(1,10) %}{{ i }} " " {% endfor %}")
>>> t.render()
'Lucky numbers 1  2  3  4  5  6  7  8  9  '
>>> 

Return templates

Import the require modules in Python

from flask import Flask, render_template

In your Flask app you can return a jinja template. Create a new program (example.py) like this. It will render the jinja template ("template.html") and pass two variables a and b.

from flask import Flask, render_template
app = Flask(__name__)


@app.route("/")
def template_test():
    return render_template('template.html', a="Hastalavista!", b=[1,2,3])


if __name__ == '__main__':
    app.run(debug=True)

Create a new directory named "templates". Inside that directory create a new file named "template.html" (see reference in code above).

You can write a complete html file, but this basic jinja template will suffice:

<p>String a is {{a}}</p>
<p>Loop through variable b</p>
<ul>
{% for x in b %}
    <li>{{x}}</li> 
{% endfor %}
</ul>

jinja

Run your program and open the url:

➜  python3 example.py
 * Serving Flask app "example" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 251-419-329

Related links:

Top comments (0)