1.. _inheritance_toplevel:
2
3===========
4Inheritance
5===========
6
7.. note::  Most of the inheritance examples here take advantage of a feature that's
8    new in Mako as of version 0.4.1 called the "block".  This tag is very similar to
9    the "def" tag but is more streamlined for usage with inheritance.  Note that
10    all of the examples here which use blocks can also use defs instead.  Contrasting
11    usages will be illustrated.
12
13Using template inheritance, two or more templates can organize
14themselves into an **inheritance chain**, where content and
15functions from all involved templates can be intermixed. The
16general paradigm of template inheritance is this: if a template
17``A`` inherits from template ``B``, then template ``A`` agrees
18to send the executional control to template ``B`` at runtime
19(``A`` is called the **inheriting** template). Template ``B``,
20the **inherited** template, then makes decisions as to what
21resources from ``A`` shall be executed.
22
23In practice, it looks like this. Here's a hypothetical inheriting
24template, ``index.html``:
25
26.. sourcecode:: mako
27
28    ## index.html
29    <%inherit file="base.html"/>
30
31    <%block name="header">
32        this is some header content
33    </%block>
34
35    this is the body content.
36
37And ``base.html``, the inherited template:
38
39.. sourcecode:: mako
40
41    ## base.html
42    <html>
43        <body>
44            <div class="header">
45                <%block name="header"/>
46            </div>
47
48            ${self.body()}
49
50            <div class="footer">
51                <%block name="footer">
52                    this is the footer
53                </%block>
54            </div>
55        </body>
56    </html>
57
58Here is a breakdown of the execution:
59
60#. When ``index.html`` is rendered, control immediately passes to
61   ``base.html``.
62#. ``base.html`` then renders the top part of an HTML document,
63   then invokes the ``<%block name="header">`` block.  It invokes the
64   underlying ``header()`` function off of a built-in namespace
65   called ``self`` (this namespace was first introduced in the
66   :doc:`Namespaces chapter <namespaces>` in :ref:`namespace_self`). Since
67   ``index.html`` is the topmost template and also defines a block
68   called ``header``, it's this ``header`` block that ultimately gets
69   executed -- instead of the one that's present in ``base.html``.
70#. Control comes back to ``base.html``. Some more HTML is
71   rendered.
72#. ``base.html`` executes ``self.body()``. The ``body()``
73   function on all template-based namespaces refers to the main
74   body of the template, therefore the main body of
75   ``index.html`` is rendered.
76#. When ``<%block name="header">`` is encountered in ``index.html``
77   during the ``self.body()`` call, a conditional is checked -- does the
78   current inherited template, i.e. ``base.html``, also define this block? If yes,
79   the ``<%block>`` is **not** executed here -- the inheritance
80   mechanism knows that the parent template is responsible for rendering
81   this block (and in fact it already has).  In other words a block
82   only renders in its *basemost scope*.
83#. Control comes back to ``base.html``. More HTML is rendered,
84   then the ``<%block name="footer">`` expression is invoked.
85#. The ``footer`` block is only defined in ``base.html``, so being
86   the topmost definition of ``footer``, it's the one that
87   executes. If ``index.html`` also specified ``footer``, then
88   its version would **override** that of the base.
89#. ``base.html`` finishes up rendering its HTML and the template
90   is complete, producing:
91
92   .. sourcecode:: html
93
94        <html>
95            <body>
96                <div class="header">
97                    this is some header content
98                </div>
99
100                this is the body content.
101
102                <div class="footer">
103                    this is the footer
104                </div>
105            </body>
106        </html>
107
108...and that is template inheritance in a nutshell. The main idea
109is that the methods that you call upon ``self`` always
110correspond to the topmost definition of that method. Very much
111the way ``self`` works in a Python class, even though Mako is
112not actually using Python class inheritance to implement this
113functionality. (Mako doesn't take the "inheritance" metaphor too
114seriously; while useful to setup some commonly recognized
115semantics, a textual template is not very much like an
116object-oriented class construct in practice).
117
118Nesting Blocks
119==============
120
121The named blocks defined in an inherited template can also be nested within
122other blocks.  The name given to each block is globally accessible via any inheriting
123template.  We can add a new block ``title`` to our ``header`` block:
124
125.. sourcecode:: mako
126
127    ## base.html
128    <html>
129        <body>
130            <div class="header">
131                <%block name="header">
132                    <h2>
133                        <%block name="title"/>
134                    </h2>
135                </%block>
136            </div>
137
138            ${self.body()}
139
140            <div class="footer">
141                <%block name="footer">
142                    this is the footer
143                </%block>
144            </div>
145        </body>
146    </html>
147
148The inheriting template can name either or both of ``header`` and ``title``, separately
149or nested themselves:
150
151.. sourcecode:: mako
152
153    ## index.html
154    <%inherit file="base.html"/>
155
156    <%block name="header">
157        this is some header content
158        ${parent.header()}
159    </%block>
160
161    <%block name="title">
162        this is the title
163    </%block>
164
165    this is the body content.
166
167Note when we overrode ``header``, we added an extra call ``${parent.header()}`` in order to invoke
168the parent's ``header`` block in addition to our own.  That's described in more detail below,
169in :ref:`parent_namespace`.
170
171Rendering a Named Block Multiple Times
172======================================
173
174Recall from the section :ref:`blocks` that a named block is just like a ``<%def>``,
175with some different usage rules.  We can call one of our named sections distinctly, for example
176a section that is used more than once, such as the title of a page:
177
178.. sourcecode:: mako
179
180    <html>
181        <head>
182            <title>${self.title()}</title>
183        </head>
184        <body>
185        <%block name="header">
186            <h2><%block name="title"/></h2>
187        </%block>
188        ${self.body()}
189        </body>
190    </html>
191
192Where above an inheriting template can define ``<%block name="title">`` just once, and it will be
193used in the base template both in the ``<title>`` section as well as the ``<h2>``.
194
195
196
197But what about Defs?
198====================
199
200The previous example used the ``<%block>`` tag to produce areas of content
201to be overridden.  Before Mako 0.4.1, there wasn't any such tag -- instead
202there was only the ``<%def>`` tag.   As it turns out, named blocks and defs are
203largely interchangeable.  The def simply doesn't call itself automatically,
204and has more open-ended naming and scoping rules that are more flexible and similar
205to Python itself, but less suited towards layout.  The first example from
206this chapter using defs would look like:
207
208.. sourcecode:: mako
209
210    ## index.html
211    <%inherit file="base.html"/>
212
213    <%def name="header()">
214        this is some header content
215    </%def>
216
217    this is the body content.
218
219And ``base.html``, the inherited template:
220
221.. sourcecode:: mako
222
223    ## base.html
224    <html>
225        <body>
226            <div class="header">
227                ${self.header()}
228            </div>
229
230            ${self.body()}
231
232            <div class="footer">
233                ${self.footer()}
234            </div>
235        </body>
236    </html>
237
238    <%def name="header()"/>
239    <%def name="footer()">
240        this is the footer
241    </%def>
242
243Above, we illustrate that defs differ from blocks in that their definition
244and invocation are defined in two separate places, instead of at once. You can *almost* do exactly what a
245block does if you put the two together:
246
247.. sourcecode:: mako
248
249    <div class="header">
250        <%def name="header()"></%def>${self.header()}
251    </div>
252
253The ``<%block>`` is obviously more streamlined than the ``<%def>`` for this kind
254of usage.  In addition,
255the above "inline" approach with ``<%def>`` does not work with nesting:
256
257.. sourcecode:: mako
258
259    <head>
260        <%def name="header()">
261            <title>
262            ## this won't work !
263            <%def name="title()">default title</%def>${self.title()}
264            </title>
265        </%def>${self.header()}
266    </head>
267
268Where above, the ``title()`` def, because it's a def within a def, is not part of the
269template's exported namespace and will not be part of ``self``.  If the inherited template
270did define its own ``title`` def at the top level, it would be called, but the "default title"
271above is not present at all on ``self`` no matter what.  For this to work as expected
272you'd instead need to say:
273
274.. sourcecode:: mako
275
276    <head>
277        <%def name="header()">
278            <title>
279            ${self.title()}
280            </title>
281        </%def>${self.header()}
282
283        <%def name="title()"/>
284    </head>
285
286That is, ``title`` is defined outside of any other defs so that it is in the ``self`` namespace.
287It works, but the definition needs to be potentially far away from the point of render.
288
289A named block is always placed in the ``self`` namespace, regardless of nesting,
290so this restriction is lifted:
291
292.. sourcecode:: mako
293
294    ## base.html
295    <head>
296        <%block name="header">
297            <title>
298            <%block name="title"/>
299            </title>
300        </%block>
301    </head>
302
303The above template defines ``title`` inside of ``header``, and an inheriting template can define
304one or both in **any** configuration, nested inside each other or not, in order for them to be used:
305
306.. sourcecode:: mako
307
308    ## index.html
309    <%inherit file="base.html"/>
310    <%block name="title">
311        the title
312    </%block>
313    <%block name="header">
314        the header
315    </%block>
316
317So while the ``<%block>`` tag lifts the restriction of nested blocks not being available externally,
318in order to achieve this it *adds* the restriction that all block names in a single template need
319to be globally unique within the template, and additionally that a ``<%block>`` can't be defined
320inside of a ``<%def>``. It's a more restricted tag suited towards a more specific use case than ``<%def>``.
321
322Using the ``next`` Namespace to Produce Content Wrapping
323========================================================
324
325Sometimes you have an inheritance chain that spans more than two
326templates. Or maybe you don't, but you'd like to build your
327system such that extra inherited templates can be inserted in
328the middle of a chain where they would be smoothly integrated.
329If each template wants to define its layout just within its main
330body, you can't just call ``self.body()`` to get at the
331inheriting template's body, since that is only the topmost body.
332To get at the body of the *next* template, you call upon the
333namespace ``next``, which is the namespace of the template
334**immediately following** the current template.
335
336Lets change the line in ``base.html`` which calls upon
337``self.body()`` to instead call upon ``next.body()``:
338
339.. sourcecode:: mako
340
341    ## base.html
342    <html>
343        <body>
344            <div class="header">
345                <%block name="header"/>
346            </div>
347
348            ${next.body()}
349
350            <div class="footer">
351                <%block name="footer">
352                    this is the footer
353                </%block>
354            </div>
355        </body>
356    </html>
357
358
359Lets also add an intermediate template called ``layout.html``,
360which inherits from ``base.html``:
361
362.. sourcecode:: mako
363
364    ## layout.html
365    <%inherit file="base.html"/>
366    <ul>
367        <%block name="toolbar">
368            <li>selection 1</li>
369            <li>selection 2</li>
370            <li>selection 3</li>
371        </%block>
372    </ul>
373    <div class="mainlayout">
374        ${next.body()}
375    </div>
376
377And finally change ``index.html`` to inherit from
378``layout.html`` instead:
379
380.. sourcecode:: mako
381
382    ## index.html
383    <%inherit file="layout.html"/>
384
385    ## .. rest of template
386
387In this setup, each call to ``next.body()`` will render the body
388of the next template in the inheritance chain (which can be
389written as ``base.html -> layout.html -> index.html``). Control
390is still first passed to the bottommost template ``base.html``,
391and ``self`` still references the topmost definition of any
392particular def.
393
394The output we get would be:
395
396.. sourcecode:: html
397
398    <html>
399        <body>
400            <div class="header">
401                this is some header content
402            </div>
403
404            <ul>
405                <li>selection 1</li>
406                <li>selection 2</li>
407                <li>selection 3</li>
408            </ul>
409
410            <div class="mainlayout">
411            this is the body content.
412            </div>
413
414            <div class="footer">
415                this is the footer
416            </div>
417        </body>
418    </html>
419
420So above, we have the ``<html>``, ``<body>`` and
421``header``/``footer`` layout of ``base.html``, we have the
422``<ul>`` and ``mainlayout`` section of ``layout.html``, and the
423main body of ``index.html`` as well as its overridden ``header``
424def. The ``layout.html`` template is inserted into the middle of
425the chain without ``base.html`` having to change anything.
426Without the ``next`` namespace, only the main body of
427``index.html`` could be used; there would be no way to call
428``layout.html``'s body content.
429
430.. _parent_namespace:
431
432Using the ``parent`` Namespace to Augment Defs
433==============================================
434
435Lets now look at the other inheritance-specific namespace, the
436opposite of ``next`` called ``parent``. ``parent`` is the
437namespace of the template **immediately preceding** the current
438template. What's useful about this namespace is that
439defs or blocks can call upon their overridden versions.
440This is not as hard as it sounds and
441is very much like using the ``super`` keyword in Python. Lets
442modify ``index.html`` to augment the list of selections provided
443by the ``toolbar`` function in ``layout.html``:
444
445.. sourcecode:: mako
446
447    ## index.html
448    <%inherit file="layout.html"/>
449
450    <%block name="header">
451        this is some header content
452    </%block>
453
454    <%block name="toolbar">
455        ## call the parent's toolbar first
456        ${parent.toolbar()}
457        <li>selection 4</li>
458        <li>selection 5</li>
459    </%block>
460
461    this is the body content.
462
463Above, we implemented a ``toolbar()`` function, which is meant
464to override the definition of ``toolbar`` within the inherited
465template ``layout.html``. However, since we want the content
466from that of ``layout.html`` as well, we call it via the
467``parent`` namespace whenever we want it's content, in this case
468before we add our own selections. So the output for the whole
469thing is now:
470
471.. sourcecode:: html
472
473    <html>
474        <body>
475            <div class="header">
476                this is some header content
477            </div>
478
479            <ul>
480                <li>selection 1</li>
481                <li>selection 2</li>
482                <li>selection 3</li>
483                <li>selection 4</li>
484                <li>selection 5</li>
485            </ul>
486
487            <div class="mainlayout">
488            this is the body content.
489            </div>
490
491            <div class="footer">
492                this is the footer
493            </div>
494        </body>
495    </html>
496
497and you're now a template inheritance ninja!
498
499Using ``<%include>`` with Template Inheritance
500==============================================
501
502A common source of confusion is the behavior of the ``<%include>`` tag,
503often in conjunction with its interaction within template inheritance.
504Key to understanding the ``<%include>`` tag is that it is a *dynamic*, e.g.
505runtime, include, and not a static include.   The ``<%include>`` is only processed
506as the template renders, and not at inheritance setup time.   When encountered,
507the referenced template is run fully as an entirely separate template with no
508linkage to any current inheritance structure.
509
510If the tag were on the other hand a *static* include, this would allow source
511within the included template to interact within the same inheritance context
512as the calling template, but currently Mako has no static include facility.
513
514In practice, this means that ``<%block>`` elements defined in an ``<%include>``
515file will not interact with corresponding ``<%block>`` elements in the calling
516template.
517
518A common mistake is along these lines:
519
520.. sourcecode:: mako
521
522    ## partials.mako
523    <%block name="header">
524        Global Header
525    </%block>
526
527    ## parent.mako
528    <%include file="partials.mako">
529
530    ## child.mako
531    <%inherit file="parent.mako">
532    <%block name="header">
533        Custom Header
534    </%block>
535
536Above, one might expect that the ``"header"`` block declared in ``child.mako``
537might be invoked, as a result of it overriding the same block present in
538``parent.mako`` via the include for ``partials.mako``.  But this is not the case.
539Instead, ``parent.mako`` will invoke ``partials.mako``, which then invokes
540``"header"`` in ``partials.mako``, and then is finished rendering.  Nothing
541from ``child.mako`` will render; there is no interaction between the ``"header"``
542block in ``child.mako`` and the ``"header"`` block in ``partials.mako``.
543
544Instead, ``parent.mako`` must explicitly state the inheritance structure.
545In order to call upon specific elements of ``partials.mako``, we will call upon
546it as a namespace:
547
548.. sourcecode:: mako
549
550    ## partials.mako
551    <%block name="header">
552        Global Header
553    </%block>
554
555    ## parent.mako
556    <%namespace name="partials" file="partials.mako"/>
557    <%block name="header">
558        ${partials.header()}
559    </%block>
560
561    ## child.mako
562    <%inherit file="parent.mako">
563    <%block name="header">
564        Custom Header
565    </%block>
566
567Where above, ``parent.mako`` states the inheritance structure that ``child.mako``
568is to participate within.  ``partials.mako`` only defines defs/blocks that can be
569used on a per-name basis.
570
571Another scenario is below, which results in both ``"SectionA"`` blocks being rendered for the ``child.mako`` document:
572
573.. sourcecode:: mako
574
575    ## base.mako
576    ${self.body()}
577    <%block name="SectionA">
578        base.mako
579    </%block>
580
581    ## parent.mako
582    <%inherit file="base.mako">
583    <%include file="child.mako">
584
585    ## child.mako
586    <%block name="SectionA">
587        child.mako
588    </%block>
589
590The resolution is similar; instead of using ``<%include>``, we call upon the blocks
591of ``child.mako`` using a namespace:
592
593.. sourcecode:: mako
594
595    ## parent.mako
596    <%inherit file="base.mako">
597    <%namespace name="child" file="child.mako">
598
599    <%block name="SectionA">
600        ${child.SectionA()}
601    </%block>
602
603
604.. _inheritance_attr:
605
606Inheritable Attributes
607======================
608
609The :attr:`attr <.Namespace.attr>` accessor of the :class:`.Namespace` object
610allows access to module level variables declared in a template. By accessing
611``self.attr``, you can access regular attributes from the
612inheritance chain as declared in ``<%! %>`` sections. Such as:
613
614.. sourcecode:: mako
615
616    <%!
617        class_ = "grey"
618    %>
619
620    <div class="${self.attr.class_}">
621        ${self.body()}
622    </div>
623
624If an inheriting template overrides ``class_`` to be
625``"white"``, as in:
626
627.. sourcecode:: mako
628
629    <%!
630        class_ = "white"
631    %>
632    <%inherit file="parent.html"/>
633
634    This is the body
635
636you'll get output like:
637
638.. sourcecode:: html
639
640    <div class="white">
641        This is the body
642    </div>
643
644.. seealso::
645
646    :ref:`namespace_attr_for_includes` - a more sophisticated example using
647    :attr:`.Namespace.attr`.
648