4 .. highlight:: html+jinja
6 This part of the documentation shows some tips and tricks for Jinja2
10 .. _null-master-fallback:
15 Jinja2 supports dynamic inheritance and does not distinguish between parent
16 and child template as long as no `extends` tag is visited. While this leads
17 to the surprising behavior that everything before the first `extends` tag
18 including whitespace is printed out instead of being igored, it can be used
21 Usually child templates extend from one template that adds a basic HTML
22 skeleton. However it's possible put the `extends` tag into an `if` tag to
23 only extend from the layout template if the `standalone` variable evaluates
24 to false which it does per default if it's not defined. Additionally a very
25 basic skeleton is added to the file so that if it's indeed rendered with
26 `standalone` set to `True` a very basic HTML skeleton is added::
28 {% if not standalone %}{% extends 'master.html' %}{% endif -%}
29 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
30 <title>{% block title %}The Page Title{% endblock %}</title>
31 <link rel="stylesheet" href="style.css" type="text/css">
33 <p>This is the page body.</p>
40 If you want to have different styles for each row of a table or
41 list you can use the `cycle` method on the `loop` object::
45 <li class="{{ loop.cycle('odd', 'even') }}">{{ row }}</li>
49 `cycle` can take an unlimited amount of strings. Each time this
50 tag is encountered the next item from the list is rendered.
53 Highlighting Active Menu Items
54 ------------------------------
56 Often you want to have a navigation bar with an active navigation
57 item. This is really simple to achieve. Because assignments outside
58 of `block`\s in child templates are global and executed before the layout
59 template is evaluated it's possible to define the active menu item in the
62 {% extends "layout.html" %}
63 {% set active_page = "index" %}
65 The layout template can then access `active_page`. Additionally it makes
66 sense to defined a default for that variable::
68 {% set navigation_bar = [
69 ('/', 'index', 'Index'),
70 ('/downloads/', 'downloads', 'Downloads'),
71 ('/about/', 'about', 'About')
73 {% set active_page = active_page|default('index') -%}
76 {% for href, id, caption in navigation_bar %}
77 <li{% if id == active_page %} class="active"{% endif
78 %}><a href="{{ href|e }}">{{ caption|e }}</a>/li>
83 .. _accessing-the-parent-loop:
85 Accessing the parent Loop
86 -------------------------
88 The special `loop` variable always points to the innermost loop. If it's
89 desired to have access to an outer loop it's possible to alias it::
92 {% for row in table %}
94 {% set rowloop = loop %}
96 <td id="cell-{{ rowloop.index }}-{{ loop.index }}>{{ cell }}</td>