Start here, and the three kinds of tags
Your plan for these four days
| Day | Module | Time |
|---|---|---|
| 1 | Templates, variables, filters and escaping | about 1.5 h |
| 2 | Inheritance, includes and macros | about 1.5 h |
| 3 | The Environment: globals, filters, i18n | about 1.5 h |
| 4 | Testing, performance, security, interview drill | about 1.5 h |
Install Jinja (pip install jinja2) and keep inpace/templates/ and the top of inpace/app.py open.
inPace has about 50 templates that all extend one base.html.
The syntax
| Tag | Does |
|---|---|
{{ ... }} |
Prints an expression |
{% ... %} |
A statement: if, for, set, block, macro... |
{# ... #} |
A comment, never sent to the browser |
<h1>{{ course.title }}</h1>
{% if progress.percent >= 100 %}
<p class="done">Finished!</p>
{% elif progress.percent %}
<progress value="{{ progress.percent }}" max="100"></progress>
{% else %}
<p>Not started yet.</p>
{% endif %}
<ul>
{% for m in course.modules %}
<li class="{{ 'open' if m.open else 'locked' }}">{{ loop.index }}. {{ m.title }}</li>
{% else %}
<li>This course has no modules.</li>
{% endfor %}
</ul>
course.titletries the attribute, thencourse["title"]: dicts and objects look the same in templates.loop.index,loop.first,loop.last,loop.lengthare available in everyfor.for ... elseruns when the list is empty.- A missing variable is Undefined: it prints as empty by default.
StrictUndefinedmakes it an error (great in tests).
Rendering from Python
from jinja2 import Environment, FileSystemLoader, select_autoescape
env = Environment(loader=FileSystemLoader("templates"), autoescape=select_autoescape(["html"]))
html = env.get_template("lesson.html").render(course=c, progress=p)