1.. _namespaces_toplevel:
2
3==========
4Namespaces
5==========
6
7Namespaces are used to organize groups of defs into
8categories, and also to "import" defs from other files.
9
10If the file ``components.html`` defines these two defs:
11
12.. sourcecode:: mako
13
14    ## components.html
15    <%def name="comp1()">
16        this is comp1
17    </%def>
18
19    <%def name="comp2(x)">
20        this is comp2, x is ${x}
21    </%def>
22
23you can make another file, for example ``index.html``, that
24pulls those two defs into a namespace called ``comp``:
25
26.. sourcecode:: mako
27
28    ## index.html
29    <%namespace name="comp" file="components.html"/>
30
31    Here's comp1:  ${comp.comp1()}
32    Here's comp2:  ${comp.comp2(x=5)}
33
34The ``comp`` variable above is an instance of
35:class:`.Namespace`, a **proxy object** which delivers
36method calls to the underlying template callable using the
37current context.
38
39``<%namespace>`` also provides an ``import`` attribute which can
40be used to pull the names into the local namespace, removing the
41need to call it via the "``.``" operator. When ``import`` is used, the
42``name`` attribute is optional.
43
44.. sourcecode:: mako
45
46    <%namespace file="components.html" import="comp1, comp2"/>
47
48    Heres comp1:  ${comp1()}
49    Heres comp2:  ${comp2(x=5)}
50
51``import`` also supports the "``*``" operator:
52
53.. sourcecode:: mako
54
55    <%namespace file="components.html" import="*"/>
56
57    Heres comp1:  ${comp1()}
58    Heres comp2:  ${comp2(x=5)}
59
60The names imported by the ``import`` attribute take precedence
61over any names that exist within the current context.
62
63.. note:: In current versions of Mako, usage of ``import='*'`` is
64   known to decrease performance of the template. This will be
65   fixed in a future release.
66
67The ``file`` argument allows expressions -- if looking for
68context variables, the ``context`` must be named explicitly:
69
70.. sourcecode:: mako
71
72    <%namespace name="dyn" file="${context['namespace_name']}"/>
73
74Ways to Call Namespaces
75=======================
76
77There are essentially four ways to call a function from a
78namespace.
79
80The "expression" format, as described previously. Namespaces are
81just Python objects with functions on them, and can be used in
82expressions like any other function:
83
84.. sourcecode:: mako
85
86    ${mynamespace.somefunction('some arg1', 'some arg2', arg3='some arg3', arg4='some arg4')}
87
88Synonymous with the "expression" format is the "custom tag"
89format, when a "closed" tag is used. This format, introduced in
90Mako 0.2.3, allows the usage of a "custom" Mako tag, with the
91function arguments passed in using named attributes:
92
93.. sourcecode:: mako
94
95    <%mynamespace:somefunction arg1="some arg1" arg2="some arg2" arg3="some arg3" arg4="some arg4"/>
96
97When using tags, the values of the arguments are taken as
98literal strings by default. To embed Python expressions as
99arguments, use the embedded expression format:
100
101.. sourcecode:: mako
102
103    <%mynamespace:somefunction arg1="${someobject.format()}" arg2="${somedef(5, 12)}"/>
104
105The "custom tag" format is intended mainly for namespace
106functions which recognize body content, which in Mako is known
107as a "def with embedded content":
108
109.. sourcecode:: mako
110
111    <%mynamespace:somefunction arg1="some argument" args="x, y">
112        Some record: ${x}, ${y}
113    </%mynamespace:somefunction>
114
115The "classic" way to call defs with embedded content is the ``<%call>`` tag:
116
117.. sourcecode:: mako
118
119    <%call expr="mynamespace.somefunction(arg1='some argument')" args="x, y">
120        Some record: ${x}, ${y}
121    </%call>
122
123For information on how to construct defs that embed content from
124the caller, see :ref:`defs_with_content`.
125
126.. _namespaces_python_modules:
127
128Namespaces from Regular Python Modules
129======================================
130
131Namespaces can also import regular Python functions from
132modules. These callables need to take at least one argument,
133``context``, an instance of :class:`.Context`. A module file
134``some/module.py`` might contain the callable:
135
136.. sourcecode:: python
137
138    def my_tag(context):
139        context.write("hello world")
140        return ''
141
142A template can use this module via:
143
144.. sourcecode:: mako
145
146    <%namespace name="hw" module="some.module"/>
147
148    ${hw.my_tag()}
149
150Note that the ``context`` argument is not needed in the call;
151the :class:`.Namespace` tag creates a locally-scoped callable which
152takes care of it. The ``return ''`` is so that the def does not
153dump a ``None`` into the output stream -- the return value of any
154def is rendered after the def completes, in addition to whatever
155was passed to :meth:`.Context.write` within its body.
156
157If your def is to be called in an "embedded content" context,
158that is as described in :ref:`defs_with_content`, you should use
159the :func:`.supports_caller` decorator, which will ensure that Mako
160will ensure the correct "caller" variable is available when your
161def is called, supporting embedded content:
162
163.. sourcecode:: python
164
165    from mako.runtime import supports_caller
166
167    @supports_caller
168    def my_tag(context):
169        context.write("<div>")
170        context['caller'].body()
171        context.write("</div>")
172        return ''
173
174Capturing of output is available as well, using the
175outside-of-templates version of the :func:`.capture` function,
176which accepts the "context" as its first argument:
177
178.. sourcecode:: python
179
180    from mako.runtime import supports_caller, capture
181
182    @supports_caller
183    def my_tag(context):
184        return "<div>%s</div>" % \
185                capture(context, context['caller'].body, x="foo", y="bar")
186
187Declaring Defs in Namespaces
188============================
189
190The ``<%namespace>`` tag supports the definition of ``<%def>``\ s
191directly inside the tag. These defs become part of the namespace
192like any other function, and will override the definitions
193pulled in from a remote template or module:
194
195.. sourcecode:: mako
196
197    ## define a namespace
198    <%namespace name="stuff">
199        <%def name="comp1()">
200            comp1
201        </%def>
202    </%namespace>
203
204    ## then call it
205    ${stuff.comp1()}
206
207.. _namespaces_body:
208
209The ``body()`` Method
210=====================
211
212Every namespace that is generated from a template contains a
213method called ``body()``. This method corresponds to the main
214body of the template, and plays its most important roles when
215using inheritance relationships as well as
216def-calls-with-content.
217
218Since the ``body()`` method is available from a namespace just
219like all the other defs defined in a template, what happens if
220you send arguments to it? By default, the ``body()`` method
221accepts no positional arguments, and for usefulness in
222inheritance scenarios will by default dump all keyword arguments
223into a dictionary called ``pageargs``. But if you actually want
224to get at the keyword arguments, Mako recommends you define your
225own argument signature explicitly. You do this via using the
226``<%page>`` tag:
227
228.. sourcecode:: mako
229
230    <%page args="x, y, someval=8, scope='foo', **kwargs"/>
231
232A template which defines the above signature requires that the
233variables ``x`` and ``y`` are defined, defines default values
234for ``someval`` and ``scope``, and sets up ``**kwargs`` to
235receive all other keyword arguments. If ``**kwargs`` or similar
236is not present, the argument ``**pageargs`` gets tacked on by
237Mako. When the template is called as a top-level template (i.e.
238via :meth:`~.Template.render`) or via the ``<%include>`` tag, the
239values for these arguments will be pulled from the ``Context``.
240In all other cases, i.e. via calling the ``body()`` method, the
241arguments are taken as ordinary arguments from the method call.
242So above, the body might be called as:
243
244.. sourcecode:: mako
245
246    ${self.body(5, y=10, someval=15, delta=7)}
247
248The :class:`.Context` object also supplies a :attr:`~.Context.kwargs`
249accessor, for cases when you'd like to pass along the top level context
250arguments to a ``body()`` callable:
251
252.. sourcecode:: mako
253
254    ${next.body(**context.kwargs)}
255
256The usefulness of calls like the above become more apparent when
257one works with inheriting templates. For more information on
258this, as well as the meanings of the names ``self`` and
259``next``, see :ref:`inheritance_toplevel`.
260
261.. _namespaces_builtin:
262
263Built-in Namespaces
264===================
265
266The namespace is so great that Mako gives your template one (or
267two) for free. The names of these namespaces are ``local`` and
268``self``. Other built-in namespaces include ``parent`` and
269``next``, which are optional and are described in
270:ref:`inheritance_toplevel`.
271
272.. _namespace_local:
273
274``local``
275---------
276
277The ``local`` namespace is basically the namespace for the
278currently executing template. This means that all of the top
279level defs defined in your template, as well as your template's
280``body()`` function, are also available off of the ``local``
281namespace.
282
283The ``local`` namespace is also where properties like ``uri``,
284``filename``, and ``module`` and the ``get_namespace`` method
285can be particularly useful.
286
287.. _namespace_self:
288
289``self``
290--------
291
292The ``self`` namespace, in the case of a template that does not
293use inheritance, is synonymous with ``local``. If inheritance is
294used, then ``self`` references the topmost template in the
295inheritance chain, where it is most useful for providing the
296ultimate form of various "method" calls which may have been
297overridden at various points in an inheritance chain. See
298:ref:`inheritance_toplevel`.
299
300Inheritable Namespaces
301======================
302
303The ``<%namespace>`` tag includes an optional attribute
304``inheritable="True"``, which will cause the namespace to be
305attached to the ``self`` namespace. Since ``self`` is globally
306available throughout an inheritance chain (described in the next
307section), all the templates in an inheritance chain can get at
308the namespace imported in a super-template via ``self``.
309
310.. sourcecode:: mako
311
312    ## base.html
313    <%namespace name="foo" file="foo.html" inheritable="True"/>
314
315    ${next.body()}
316
317    ## somefile.html
318    <%inherit file="base.html"/>
319
320    ${self.foo.bar()}
321
322This allows a super-template to load a whole bunch of namespaces
323that its inheriting templates can get to, without them having to
324explicitly load those namespaces themselves.
325
326The ``import="*"`` part of the ``<%namespace>`` tag doesn't yet
327interact with the ``inheritable`` flag, so currently you have to
328use the explicit namespace name off of ``self``, followed by the
329desired function name. But more on this in a future release.
330
331Namespace API Usage Example - Static Dependencies
332==================================================
333
334The ``<%namespace>`` tag at runtime produces an instance of
335:class:`.Namespace`.   Programmatic access of :class:`.Namespace` can be used
336to build various kinds of scaffolding in templates and between templates.
337
338A common request is the ability for a particular template to declare
339"static includes" - meaning, the usage of a particular set of defs requires
340that certain Javascript/CSS files are present.   Using :class:`.Namespace` as the
341object that holds together the various templates present, we can build a variety
342of such schemes.   In particular, the :class:`.Context` has a ``namespaces``
343attribute, which is a dictionary of all :class:`.Namespace` objects declared.
344Iterating the values of this dictionary will provide a :class:`.Namespace`
345object for each time the ``<%namespace>`` tag was used, anywhere within the
346inheritance chain.
347
348
349.. _namespace_attr_for_includes:
350
351Version One - Use :attr:`.Namespace.attr`
352-----------------------------------------
353
354The :attr:`.Namespace.attr` attribute allows us to locate any variables declared
355in the ``<%! %>`` of a template.
356
357.. sourcecode:: mako
358
359    ## base.mako
360    ## base-most template, renders layout etc.
361    <html>
362    <head>
363    ## traverse through all namespaces present,
364    ## look for an attribute named 'includes'
365    % for ns in context.namespaces.values():
366        % for incl in getattr(ns.attr, 'includes', []):
367            ${incl}
368        % endfor
369    % endfor
370    </head>
371    <body>
372    ${next.body()}
373    </body
374    </html>
375
376    ## library.mako
377    ## library functions.
378    <%!
379        includes = [
380            '<link rel="stylesheet" type="text/css" href="mystyle.css"/>',
381            '<script type="text/javascript" src="functions.js"></script>'
382        ]
383    %>
384
385    <%def name="mytag()">
386        <form>
387            ${caller.body()}
388        </form>
389    </%def>
390
391    ## index.mako
392    ## calling template.
393    <%inherit file="base.mako"/>
394    <%namespace name="foo" file="library.mako"/>
395
396    <%foo:mytag>
397        a form
398    </%foo:mytag>
399
400
401Above, the file ``library.mako`` declares an attribute ``includes`` inside its global ``<%! %>`` section.
402``index.mako`` includes this template using the ``<%namespace>`` tag.  The base template ``base.mako``, which is the inherited parent of ``index.mako`` and is responsible for layout, then locates this attribute and iterates through its contents to produce the includes that are specific to ``library.mako``.
403
404Version Two - Use a specific named def
405-----------------------------------------
406
407In this version, we put the includes into a ``<%def>`` that
408follows a naming convention.
409
410.. sourcecode:: mako
411
412    ## base.mako
413    ## base-most template, renders layout etc.
414    <html>
415    <head>
416    ## traverse through all namespaces present,
417    ## look for a %def named 'includes'
418    % for ns in context.namespaces.values():
419        % if hasattr(ns, 'includes'):
420            ${ns.includes()}
421        % endif
422    % endfor
423    </head>
424    <body>
425    ${next.body()}
426    </body
427    </html>
428
429    ## library.mako
430    ## library functions.
431
432    <%def name="includes()">
433        <link rel="stylesheet" type="text/css" href="mystyle.css"/>
434        <script type="text/javascript" src="functions.js"></script>
435    </%def>
436
437    <%def name="mytag()">
438        <form>
439            ${caller.body()}
440        </form>
441    </%def>
442
443
444    ## index.mako
445    ## calling template.
446    <%inherit file="base.mako"/>
447    <%namespace name="foo" file="library.mako"/>
448
449    <%foo:mytag>
450        a form
451    </%foo:mytag>
452
453In this version, ``library.mako`` declares a ``<%def>`` named ``includes``.   The example works
454identically to the previous one, except that ``base.mako`` looks for defs named ``include``
455on each namespace it examines.
456
457API Reference
458=============
459
460.. autoclass:: mako.runtime.Namespace
461    :show-inheritance:
462    :members:
463
464.. autoclass:: mako.runtime.TemplateNamespace
465    :show-inheritance:
466    :members:
467
468.. autoclass:: mako.runtime.ModuleNamespace
469    :show-inheritance:
470    :members:
471
472.. autofunction:: mako.runtime.supports_caller
473
474.. autofunction:: mako.runtime.capture
475
476