You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5.2 KiB

Jinja templates

In [ ]:
from jinja2 import Template 

Jinja

https://jinja.palletsprojects.com/en/2.11.x/

Jinja is a modern and designer-friendly templating language for Python (...). It is fast, widely used and secure with the optional sandboxed template execution environment:

In [ ]:
# Basic usage of Jinja
template = Template('Hello {{ name }}!')
you = 'XPUB1'
output = template.render(name=you)
print(output)
In [ ]:
# Jinja is very useful for generating HTML pages
# Let's start with a HTML snippet: 
template = Template('<h1>Hello {{ name }}!</h1>')
you = 'XPUB1'
html = template.render(name=you)
print(html)
In [ ]:
# But these templates can be much longer.
# Let's now use a separate jinja-template.html file, as our template:
template_file = open('jinja-template.html').read()
template = Template(template_file)
you = 'XPUB1'
html = template.render(name=you)
print(html)
In [ ]:
 

For loops & if / else

For loops

For loops are written in a pythonic way.

What is different, is the "closing tag" {% endfor %}.

{% for item in list %}

    {{ item }}

{% endfor %}
In [ ]:
template = Template('''

<h1>Hello to</h1>

{% for name in XPUB1 %}

    <h2>{{ name  }}<h2>

{% endfor %}

''')
XPUB1 = ['you', 'you', 'you']
html = template.render(XPUB1=XPUB1)
print(html)
In [ ]:
# Or display it in HTML here in the notebook directly :)
from IPython.core.display import HTML
HTML(html)
In [ ]:
 

if / else

Also if / else statements are written in a pythonic way.

The only thing again that is new, is the "closing tag" {% endif %}.

{% for item in list %}

    {% if 'hello' in item %}

        <h1>HELLO</h1>

    {% else %}

        {{ item }}

    {% endif %}

{% endfor %}
In [ ]:
template = Template('''

<h1>Hello to</h1>

{% for name in XPUB1 %}

    {% if name == 'me' %}

        <h2 style="color:magenta;">{{ name  }}<h2>
    
    {% else %}

        <h2>{{ name  }}<h2>
        
    {% endif %}

{% endfor %}

''')
XPUB1 = ['you', 'me', 'you']
html = template.render(XPUB1=XPUB1)
HTML(html)
In [ ]:
 
In [ ]:
 

Further diving

More syntax details can be found here: https://jinja.palletsprojects.com/en/2.11.x/templates/

In [ ]: