1.. _syntax_toplevel:
2
3======
4Syntax
5======
6
7A Mako template is parsed from a text stream containing any kind
8of content, XML, HTML, email text, etc. The template can further
9contain Mako-specific directives which represent variable and/or
10expression substitutions, control structures (i.e. conditionals
11and loops), server-side comments, full blocks of Python code, as
12well as various tags that offer additional functionality. All of
13these constructs compile into real Python code. This means that
14you can leverage the full power of Python in almost every aspect
15of a Mako template.
16
17Expression Substitution
18=======================
19
20The simplest expression is just a variable substitution. The
21syntax for this is the ``${}`` construct, which is inspired by
22Perl, Genshi, JSP EL, and others:
23
24.. sourcecode:: mako
25
26    this is x: ${x}
27
28Above, the string representation of ``x`` is applied to the
29template's output stream. If you're wondering where ``x`` comes
30from, it's usually from the :class:`.Context` supplied to the
31template's rendering function. If ``x`` was not supplied to the
32template and was not otherwise assigned locally, it evaluates to
33a special value ``UNDEFINED``. More on that later.
34
35The contents within the ``${}`` tag are evaluated by Python
36directly, so full expressions are OK:
37
38.. sourcecode:: mako
39
40    pythagorean theorem:  ${pow(x,2) + pow(y,2)}
41
42The results of the expression are evaluated into a string result
43in all cases before being rendered to the output stream, such as
44the above example where the expression produces a numeric
45result.
46
47Expression Escaping
48===================
49
50Mako includes a number of built-in escaping mechanisms,
51including HTML, URI and XML escaping, as well as a "trim"
52function. These escapes can be added to an expression
53substitution using the ``|`` operator:
54
55.. sourcecode:: mako
56
57    ${"this is some text" | u}
58
59The above expression applies URL escaping to the expression, and
60produces ``this+is+some+text``. The ``u`` name indicates URL
61escaping, whereas ``h`` represents HTML escaping, ``x``
62represents XML escaping, and ``trim`` applies a trim function.
63
64Read more about built-in filtering functions, including how to
65make your own filter functions, in :ref:`filtering_toplevel`.
66
67Control Structures
68==================
69
70A control structure refers to all those things that control the
71flow of a program -- conditionals (i.e. ``if``/``else``), loops (like
72``while`` and ``for``), as well as things like ``try``/``except``. In Mako,
73control structures are written using the ``%`` marker followed
74by a regular Python control expression, and are "closed" by
75using another ``%`` marker with the tag "``end<name>``", where
76"``<name>``" is the keyword of the expression:
77
78.. sourcecode:: mako
79
80    % if x==5:
81        this is some output
82    % endif
83
84The ``%`` can appear anywhere on the line as long as no text
85precedes it; indentation is not significant. The full range of
86Python "colon" expressions are allowed here, including
87``if``/``elif``/``else``, ``while``, ``for``, ``with``, and even ``def``,
88although Mako has a built-in tag for defs which is more full-featured.
89
90.. sourcecode:: mako
91
92    % for a in ['one', 'two', 'three', 'four', 'five']:
93        % if a[0] == 't':
94        its two or three
95        % elif a[0] == 'f':
96        four/five
97        % else:
98        one
99        % endif
100    % endfor
101
102The ``%`` sign can also be "escaped", if you actually want to
103emit a percent sign as the first non whitespace character on a
104line, by escaping it as in ``%%``:
105
106.. sourcecode:: mako
107
108    %% some text
109
110        %% some more text
111
112The Loop Context
113----------------
114
115The **loop context** provides additional information about a loop
116while inside of a ``% for`` structure:
117
118.. sourcecode:: mako
119
120    <ul>
121    % for a in ("one", "two", "three"):
122        <li>Item ${loop.index}: ${a}</li>
123    % endfor
124    </ul>
125
126See :ref:`loop_context` for more information on this feature.
127
128.. versionadded:: 0.7
129
130Comments
131========
132
133Comments come in two varieties. The single line comment uses
134``##`` as the first non-space characters on a line:
135
136.. sourcecode:: mako
137
138    ## this is a comment.
139    ...text ...
140
141A multiline version exists using ``<%doc> ...text... </%doc>``:
142
143.. sourcecode:: mako
144
145    <%doc>
146        these are comments
147        more comments
148    </%doc>
149
150Newline Filters
151===============
152
153The backslash ("``\``") character, placed at the end of any
154line, will consume the newline character before continuing to
155the next line:
156
157.. sourcecode:: mako
158
159    here is a line that goes onto \
160    another line.
161
162The above text evaluates to:
163
164.. sourcecode:: text
165
166    here is a line that goes onto another line.
167
168Python Blocks
169=============
170
171Any arbitrary block of python can be dropped in using the ``<%
172%>`` tags:
173
174.. sourcecode:: mako
175
176    this is a template
177    <%
178        x = db.get_resource('foo')
179        y = [z.element for z in x if x.frobnizzle==5]
180    %>
181    % for elem in y:
182        element: ${elem}
183    % endfor
184
185Within ``<% %>``, you're writing a regular block of Python code.
186While the code can appear with an arbitrary level of preceding
187whitespace, it has to be consistently formatted with itself.
188Mako's compiler will adjust the block of Python to be consistent
189with the surrounding generated Python code.
190
191Module-level Blocks
192===================
193
194A variant on ``<% %>`` is the module-level code block, denoted
195by ``<%! %>``. Code within these tags is executed at the module
196level of the template, and not within the rendering function of
197the template. Therefore, this code does not have access to the
198template's context and is only executed when the template is
199loaded into memory (which can be only once per application, or
200more, depending on the runtime environment). Use the ``<%! %>``
201tags to declare your template's imports, as well as any
202pure-Python functions you might want to declare:
203
204.. sourcecode:: mako
205
206    <%!
207        import mylib
208        import re
209
210        def filter(text):
211            return re.sub(r'^@', '', text)
212    %>
213
214Any number of ``<%! %>`` blocks can be declared anywhere in a
215template; they will be rendered in the resulting module
216in a single contiguous block above all render callables,
217in the order in which they appear in the source template.
218
219Tags
220====
221
222The rest of what Mako offers takes place in the form of tags.
223All tags use the same syntax, which is similar to an XML tag
224except that the first character of the tag name is a ``%``
225character. The tag is closed either by a contained slash
226character, or an explicit closing tag:
227
228.. sourcecode:: mako
229
230    <%include file="foo.txt"/>
231
232    <%def name="foo" buffered="True">
233        this is a def
234    </%def>
235
236All tags have a set of attributes which are defined for each
237tag. Some of these attributes are required. Also, many
238attributes support **evaluation**, meaning you can embed an
239expression (using ``${}``) inside the attribute text:
240
241.. sourcecode:: mako
242
243    <%include file="/foo/bar/${myfile}.txt"/>
244
245Whether or not an attribute accepts runtime evaluation depends
246on the type of tag and how that tag is compiled into the
247template. The best way to find out if you can stick an
248expression in is to try it! The lexer will tell you if it's not
249valid.
250
251Heres a quick summary of all the tags:
252
253``<%page>``
254-----------
255
256This tag defines general characteristics of the template,
257including caching arguments, and optional lists of arguments
258which the template expects when invoked.
259
260.. sourcecode:: mako
261
262    <%page args="x, y, z='default'"/>
263
264Or a page tag that defines caching characteristics:
265
266.. sourcecode:: mako
267
268    <%page cached="True" cache_type="memory"/>
269
270Currently, only one ``<%page>`` tag gets used per template, the
271rest get ignored. While this will be improved in a future
272release, for now make sure you have only one ``<%page>`` tag
273defined in your template, else you may not get the results you
274want.  Further details on what ``<%page>`` is used for are described
275in the following sections:
276
277* :ref:`namespaces_body` - ``<%page>`` is used to define template-level
278  arguments and defaults
279
280* :ref:`expression_filtering` - expression filters can be applied to all
281  expressions throughout a template using the ``<%page>`` tag
282
283* :ref:`caching_toplevel` - options to control template-level caching
284  may be applied in the ``<%page>`` tag.
285
286``<%include>``
287--------------
288
289A tag that is familiar from other template languages, ``%include``
290is a regular joe that just accepts a file argument and calls in
291the rendered result of that file:
292
293.. sourcecode:: mako
294
295    <%include file="header.html"/>
296
297        hello world
298
299    <%include file="footer.html"/>
300
301Include also accepts arguments which are available as ``<%page>`` arguments in the receiving template:
302
303.. sourcecode:: mako
304
305    <%include file="toolbar.html" args="current_section='members', username='ed'"/>
306
307``<%def>``
308----------
309
310The ``%def`` tag defines a Python function which contains a set
311of content, that can be called at some other point in the
312template. The basic idea is simple:
313
314.. sourcecode:: mako
315
316    <%def name="myfunc(x)">
317        this is myfunc, x is ${x}
318    </%def>
319
320    ${myfunc(7)}
321
322The ``%def`` tag is a lot more powerful than a plain Python ``def``, as
323the Mako compiler provides many extra services with ``%def`` that
324you wouldn't normally have, such as the ability to export defs
325as template "methods", automatic propagation of the current
326:class:`.Context`, buffering/filtering/caching flags, and def calls
327with content, which enable packages of defs to be sent as
328arguments to other def calls (not as hard as it sounds). Get the
329full deal on what ``%def`` can do in :ref:`defs_toplevel`.
330
331``<%block>``
332------------
333
334``%block`` is a tag that is close to a ``%def``,
335except executes itself immediately in its base-most scope,
336and can also be anonymous (i.e. with no name):
337
338.. sourcecode:: mako
339
340    <%block filter="h">
341        some <html> stuff.
342    </%block>
343
344Inspired by Jinja2 blocks, named blocks offer a syntactically pleasing way
345to do inheritance:
346
347.. sourcecode:: mako
348
349    <html>
350        <body>
351        <%block name="header">
352            <h2><%block name="title"/></h2>
353        </%block>
354        ${self.body()}
355        </body>
356    </html>
357
358Blocks are introduced in :ref:`blocks` and further described in :ref:`inheritance_toplevel`.
359
360.. versionadded:: 0.4.1
361
362``<%namespace>``
363----------------
364
365``%namespace`` is Mako's equivalent of Python's ``import``
366statement. It allows access to all the rendering functions and
367metadata of other template files, plain Python modules, as well
368as locally defined "packages" of functions.
369
370.. sourcecode:: mako
371
372    <%namespace file="functions.html" import="*"/>
373
374The underlying object generated by ``%namespace``, an instance of
375:class:`.mako.runtime.Namespace`, is a central construct used in
376templates to reference template-specific information such as the
377current URI, inheritance structures, and other things that are
378not as hard as they sound right here. Namespaces are described
379in :ref:`namespaces_toplevel`.
380
381``<%inherit>``
382--------------
383
384Inherit allows templates to arrange themselves in **inheritance
385chains**. This is a concept familiar in many other template
386languages.
387
388.. sourcecode:: mako
389
390    <%inherit file="base.html"/>
391
392When using the ``%inherit`` tag, control is passed to the topmost
393inherited template first, which then decides how to handle
394calling areas of content from its inheriting templates. Mako
395offers a lot of flexibility in this area, including dynamic
396inheritance, content wrapping, and polymorphic method calls.
397Check it out in :ref:`inheritance_toplevel`.
398
399``<%``\ nsname\ ``:``\ defname\ ``>``
400-------------------------------------
401
402Any user-defined "tag" can be created against
403a namespace by using a tag with a name of the form
404``<%<namespacename>:<defname>>``. The closed and open formats of such a
405tag are equivalent to an inline expression and the ``<%call>``
406tag, respectively.
407
408.. sourcecode:: mako
409
410    <%mynamespace:somedef param="some value">
411        this is the body
412    </%mynamespace:somedef>
413
414To create custom tags which accept a body, see
415:ref:`defs_with_content`.
416
417.. versionadded:: 0.2.3
418
419``<%call>``
420-----------
421
422The call tag is the "classic" form of a user-defined tag, and is
423roughly equivalent to the ``<%namespacename:defname>`` syntax
424described above. This tag is also described in :ref:`defs_with_content`.
425
426``<%doc>``
427----------
428
429The ``%doc`` tag handles multiline comments:
430
431.. sourcecode:: mako
432
433    <%doc>
434        these are comments
435        more comments
436    </%doc>
437
438Also the ``##`` symbol as the first non-space characters on a line can be used for single line comments.
439
440``<%text>``
441-----------
442
443This tag suspends the Mako lexer's normal parsing of Mako
444template directives, and returns its entire body contents as
445plain text. It is used pretty much to write documentation about
446Mako:
447
448.. sourcecode:: mako
449
450    <%text filter="h">
451        heres some fake mako ${syntax}
452        <%def name="x()">${x}</%def>
453    </%text>
454
455.. _syntax_exiting_early:
456
457Exiting Early from a Template
458=============================
459
460Sometimes you want to stop processing a template or ``<%def>``
461method in the middle and just use the text you've accumulated so
462far.  This is accomplished by using ``return`` statement inside
463a Python block.   It's a good idea for the ``return`` statement
464to return an empty string, which prevents the Python default return
465value of ``None`` from being rendered by the template.  This
466return value is for semantic purposes provided in templates via
467the ``STOP_RENDERING`` symbol:
468
469.. sourcecode:: mako
470
471    % if not len(records):
472        No records found.
473        <% return STOP_RENDERING %>
474    % endif
475
476Or perhaps:
477
478.. sourcecode:: mako
479
480    <%
481        if not len(records):
482            return STOP_RENDERING
483    %>
484
485In older versions of Mako, an empty string can be substituted for
486the ``STOP_RENDERING`` symbol:
487
488.. sourcecode:: mako
489
490    <% return '' %>
491
492.. versionadded:: 1.0.2 - added the ``STOP_RENDERING`` symbol which serves
493   as a semantic identifier for the empty string ``""`` used by a
494   Python ``return`` statement.
495
496