# -*- coding: utf-8 -*- <%inherit file="content_layout.html"/> <%page args="toc, extension, paged"/> <%namespace name="formatting" file="formatting.html"/> <%namespace name="nav" file="nav.html"/> <%def name="title()">Mako Documentation - Defs <%! filename = 'defs' %> ## This file is generated. Edit the .txt files instead of this one. <%call expr="formatting.section(path='defs',paged=paged,extension=extension,toc=toc)">

The def is the single tag used to demarcate any block of text and/or code. It exists within generated Python as a callable function.

<%call expr="formatting.code()"><%text><%def name="hello()"> hello world

They are normally called as expressions.

<%call expr="formatting.code()"><%text>the def: ${hello()}

If the <%text filter='h'><%def> is not nested inside of another <%text filter='h'><%def>, its known as a top level def and can be accessed anywhere in the template, including above where it was defined.

All defs, top level or not, have access to the current contextual namespace in exactly the same way their containing template does. Suppose the template below is executed with the variables <%text filter='h'>username and <%text filter='h'>accountdata inside the context:

<%call expr="formatting.code()"><%text>Hello there ${username}, how are ya. Lets see what your account says: ${account()} <%def name="account()"> Account for ${username}:
% for row in accountdata: Value: ${row}
% endfor

The <%text filter='h'>username and <%text filter='h'>accountdata variables are present within the main template body as well as the body of the <%text filter='h'>account() def.

Since defs are just Python functions, you can define and pass arguments to them as well:

<%call expr="formatting.code()"><%text>${account(accountname='john')} <%def name="account(accountname, type='regular')"> account name: ${accountname}, type ${type}

When you declare an argument signature for your def, they are required to follow normal Python conventions (i.e., all arguments are required except keyword arguments with a default value). This is in contrast to using context-level variables, which evaluate to <%text filter='h'>UNDEFINED if you reference a name that does not exist.

<%call expr="formatting.section(path='defs_remotedefs',paged=paged,extension=extension,toc=toc)">

Top level <%text filter='h'><%defs> are exported by your template's module, and can be called from the outside; including from other templates, as well as normal Python code. Calling a <%text filter='h'><%def> from another template is something like using an <%text filter='h'><%include> - except you are calling a specific function within the template, not the whole template.

The remote <%text filter='h'><%def> call is also a little bit like calling functions from other modules in Python. There is an "import" step to pull the names from another template into your own template; then the function or functions are available.

To import another template, use the <%text filter='h'><%namespace> tag:

<%call expr="formatting.code()"><%text><%namespace name="mystuff" file="mystuff.html"/>

The above tag adds a local variable "mystuff" to the current scope.

Then, just call the defs off of <%text filter='h'>mystuff:

<%call expr="formatting.code()"><%text>${mystuff.somedef(x=5,y=7)}

The <%text filter='h'><%namespace> tag also supports some of the other semantics of Python's <%text filter='h'>import statement, including pulling names into the local variable space, or using <%text filter='h'>* to represent all names, using the <%text filter='h'>import attribute:

<%call expr="formatting.code()"><%text><%namespace file="mystuff.html" import="foo, bar"/>

This is just a quick intro to the concept of a namespace, which is a central Mako concept that has its own chapter in these docs. For more detail and examples, see <%call expr="nav.toclink(path='namespaces',paged=paged,extension=extension,toc=toc)">.

<%call expr="formatting.section(path='defs_programmatic',paged=paged,extension=extension,toc=toc)">

You can call def's programmatically from any <%text filter='h'>Template object using the <%text filter='h'>get_def() method, which returns a <%text filter='h'>DefTemplate object. This is a <%text filter='h'>Template subclass which the parent <%text filter='h'>Template creates, and is usable like any other template:

<%call expr="formatting.code(syntaxtype='python')"><%text> from mako.template import Template template = Template(""" <%def name="hi(name)"> hi ${name}! <%def name="bye(name)"> bye ${name}! """) print template.get_def("hi").render(name="ed") print template.get_def("bye").render(name="ed") <%call expr="formatting.section(path='defs_nesteddefs',paged=paged,extension=extension,toc=toc)">

The def model follows regular Python rules for closures. Declaring <%text filter='h'><%def> inside another <%text filter='h'><%def> declares it within the parent's enclosing scope:

<%call expr="formatting.code()"><%text><%def name="mydef()"> <%def name="subdef()"> a sub def im the def, and the subcomopnent is ${subdef()}

Just like Python, names that exist outside the inner <%text filter='h'><%def> exist inside it as well:

<%call expr="formatting.code()"><%text><% x = 12 %> <%def name="outer()"> <% y = 15 %> <%def name="inner()"> inner, x is ${x}, y is ${y} outer, x is ${x}, y is ${y}

Assigning to a name inside of a def declares that name as local to the scope of that def (again, like Python itself). This means the following code will raise an error:

<%call expr="formatting.code()"><%text><% x = 10 %> <%def name="somedef()"> ## error ! somedef, x is ${x} <% x = 27 %>

...because the assignment to <%text filter='h'>x declares x as local to the scope of <%text filter='h'>somedef, rendering the "outer" version unreachable in the expression that tries to render it.

<%call expr="formatting.section(path='defs_defswithcontent',paged=paged,extension=extension,toc=toc)">

A flip-side to def within def is a def call with content. This is where you call a def, and at the same time declare a block of content (or multiple blocks) that can be used by the def being called. The main point of such a call is to create custom, nestable tags, just like any other template language's custom-tag creation system - where the external tag controls the execution of the nested tags and can communicate state to them. Only with Mako, you don't have to use any external Python modules, you can define arbitrarily nestable tags right in your templates.

To achieve this, the target def is invoked using the form <%text filter='h'><%namepacename:defname> instead of the normal <%text filter='h'>${} syntax. This syntax, introduced in Mako 0.2.3, is functionally equivalent another tag known as <%text filter='h'>call, which takes the form <%text filter='h'><%call expr='namespacename.defname(args)'>. While <%text filter='h'>%call is available in all versions of Mako, the newer style is probably more familiar looking. The <%text filter='h'>namespace portion of the call is the name of the namespace in which the def is defined - in the most simple cases, this can be <%text filter='h'>local or <%text filter='h'>self to reference the current template's namespace (the difference between <%text filter='h'>local and <%text filter='h'>self is one of inheritance - see <%call expr="nav.toclink(path='namespaces_builtin',paged=paged,extension=extension,toc=toc)"> for details).

When the target def is invoked, a variable <%text filter='h'>caller is placed in its context which contains another namespace containing the body and other defs defined by the caller. The body itself is referenced by the method <%text filter='h'>body(). Below, we build a <%text filter='h'>%def that operates upon <%text filter='h'>caller.body() to invoke the body of the custom tag:

<%call expr="formatting.code()"><%text><%def name="buildtable()">
${caller.body()}
<%self:buildtable> I am the table body.

This produces the output (whitespace formatted):

<%call expr="formatting.code(syntaxtype='html')"><%text>
I am the table body.

Using the older <%text filter='h'>%call syntax looks like:

<%call expr="formatting.code()"><%text><%def name="buildtable()">
${caller.body()}
<%call expr="buildtable()"> I am the table body.

The <%text filter='h'>body() can be executed multiple times or not at all. This means you can use def-call-with-content to build iterators, conditionals, etc:

<%call expr="formatting.code()"><%text><%def name="lister(count)"> % for x in range(count): ${caller.body()} % endfor <%self:lister count="${3}"> hi

Produces:

<%call expr="formatting.code(syntaxtype='html')"><%text> hi hi hi

Notice above we pass <%text filter='h'>3 as a Python expression, so that it remains as an integer.

A custom "conditional" tag:

<%call expr="formatting.code()"><%text><%def name="conditional(expression)"> % if expression: ${caller.body()} % endif <%self:conditional expression="${4==4}"> im the result

Produces:

<%call expr="formatting.code(syntaxtype='html')"><%text> im the result

But that's not all. The <%text filter='h'>body() function also can handle arguments, which will augment the local namespace of the body callable. The caller must define the arguments which it expects to receive from its target def using the <%text filter='h'>args attribute, which is a comma-separated list of argument names. Below, our <%text filter='h'><%def> calls the <%text filter='h'>body() of its caller, passing in an element of data from its argument:

<%call expr="formatting.code()"><%text><%def name="layoutdata(somedata)"> % for item in somedata: % for col in item: % endfor % endfor
${caller.body(col=col)}
<%self:layoutdata somedata="${[[1,2,3],[4,5,6],[7,8,9]]}" args="col">\ Body data: ${col}\

Produces:

<%call expr="formatting.code(syntaxtype='html')"><%text>
Body data: 1 Body data: 2 Body data: 3
Body data: 4 Body data: 5 Body data: 6
Body data: 7 Body data: 8 Body data: 9

You don't have to stick to calling just the <%text filter='h'>body() function. The caller can define any number of callables, allowing the <%text filter='h'><%call> tag to produce whole layouts:

<%call expr="formatting.code()"><%text><%def name="layout()"> ## a layout def
${caller.header()}
${caller.body()}
## calls the layout def <%self:layout> <%def name="header()"> I am the header <%def name="sidebar()"> this is the body

The above layout would produce:

<%call expr="formatting.code()"><%text>
I am the header
this is the body

The number of things you can do with <%text filter='h'><%call> and/or the <%text filter='h'><%namespacename:defname> calling syntax is enormous. You can create form widget libraries, such as an enclosing <%text filter='h'>

tag and nested HTML input elements, or portable wrapping schemes using <%text filter='h'>
or other elements. You can create tags that interpret rows of data, such as from a database, providing the individual columns of each row to a <%text filter='h'>body() callable which lays out the row any way it wants. Basically anything you'd do with a "custom tag" or tag library in some other system, Mako provides via <%text filter='h'><%def>s and plain Python callables which are invoked via <%text filter='h'><%namespacename:defname> or <%text filter='h'><%call>.