Ben Chuanlong Du's Blog

It is never too late to learn.

Tips on Jinja

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

In [2]:
!pip3 install jinja2
Requirement already satisfied: jinja2 in /usr/local/lib/python3.8/site-packages (2.11.2)
Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.8/site-packages (from jinja2) (1.1.1)
In [5]:
from jinja2 import Template
from argparse import Namespace
In [6]:
template = Template("Hello {{ name }}!")
template.render(name="John Doe")
Out[6]:
'Hello John Doe!'
In [9]:
s = """<title>{% block title %}{% endblock %}</title>
    <ul>
    {% for user in users %}
    <li><a href="{{ user.url }}">{{ user.username }}</a></li>
    {% endfor %}
    </ul>
    """
s = Template(s).render(users=[Namespace(username="Ben", url="www.legendu.net")])
print(s)
<title></title>
    <ul>
    
    <li><a href="www.legendu.net">Ben</a></li>
    
    </ul>
    
In [ ]:

Comments