Skip to content

Instantly share code, notes, and snippets.

@dunderrrrrr
Created February 21, 2020 13:44
Show Gist options
  • Save dunderrrrrr/acef5882fe79675ac28053de4efed8f4 to your computer and use it in GitHub Desktop.
Save dunderrrrrr/acef5882fe79675ac28053de4efed8f4 to your computer and use it in GitHub Desktop.
Jinja2 is one of the most used template engines for Python.

Jinja2 is one of the most used template engines for Python. It is inspired by Django's templating system but extends it with an expressive language that gives template authors a more powerful set of tools. On top of that it adds sandboxed execution and optional automatic escaping for applications where security is important.

Installing

Usually this is done inside a python virtualenv.

$ pip install jinja2

Usage

Every time though I have to spend some time figuring out how to lay out my files and how to load the template. So here is an example that you can also use as a skeleton for your next application.

.
├── run.py
├── html
│   └── index.html
└── templates
    └── index.html

run.py

from jinja2 import Environment, FileSystemLoader
import os
 
root = os.path.dirname(os.path.abspath(__file__))
templates_dir = os.path.join(root, 'templates')
env = Environment( loader = FileSystemLoader(templates_dir) )
template = env.get_template('index.html')
 
 
filename = os.path.join(root, 'html', 'index.html')
with open(filename, 'w') as fh:
    fh.write(template.render(
        h1 = "Hello Jinja2",
        show_one = True,
        show_two = False,
        names    = ["Foo", "Bar", "Qux"],
    ))

templates/index.html

<h1>{{ h1 }}</h1>
 
{% if show_one %}
  <h2>one</h2>
{% endif %}
 
{% if show_two %}
  <h2>two</h2>
{% endif %}
 
<ul>
{% for name in names %}
   <li>{{ name }}</li>
{% endfor %}
</ul>

Output

When run.py is executed html/index.html will have the following contents.

<h1>Hello Jinja2</h1>
  <h2>one</h2>
<ul>
   <li>Foo</li>
   <li>Bar</li>
   <li>Qux</li>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment