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.

55 lines
1.7 KiB
Python

# RENDER TEMPLATE:
# http://jinja.pocoo.org/docs/2.10/intro/#basic-api-usage
from jinja2 import Template
htmlfragment = """<h1 id='{{id}}'>
{{ content }}
</h1>
"""
template = Template(htmlfragment)
title = template.render(content="XPuB tries JINJA (What??)",
id="elementid")
# print(htmlrendered)
# CONTROL STRUCTURES: loops and if conditions
# http://jinja.pocoo.org/docs/2.10/templates/#list-of-control-structures
users_html = Template('''<ul>
{% for user in users %}
<li class="user" id="user_{{ user|lower }}">
{% if user[0] == "A" %}
<i>{{ user[0] }}</i>{{ user[1:] }}
{% else %}
<b>{{ user[0] }}</b>{{ user[1:] }}
{% endif %}
</li>
{% endfor %}
</ul>
''')
xpub1 = ["Pedro", "Rita", "Simon", "Artemis", "Bo", "Biyi", "Tancredi"]
xpub2 = ["Tash", "Angeliki", "Alice", "Alex", "Joca", "Zalan"]
# render the same template with 2 different lists, a string
users_1 = users_html.render(users=xpub1)
users_2 = users_html.render(users=xpub2)
users_2 = users_html.render(users="xpub2")
# print(users_1, users_2)
# TEMPLATE-INHERITANCE
# http://jinja.pocoo.org/docs/2.10/templates/#template-inheritance
from jinja2 import FileSystemLoader
from jinja2.environment import Environment
env = Environment() # loads templates from the file system
env.loader = FileSystemLoader('.') # Loads templates from the current directory
tmpl = env.get_template('child.html') # get the template # which itself inherit base.html template
tmpl_render = tmpl.render(mytitle="xpUB",
content=title + users_1 + users_2) # render the template
print(tmpl_render)
# save
with open("index.html", "w") as index:
index.write(tmpl_render)