1.. _defs_toplevel: 2 3=============== 4Defs and Blocks 5=============== 6 7``<%def>`` and ``<%block>`` are two tags that both demarcate any block of text 8and/or code. They both exist within generated Python as a callable function, 9i.e., a Python ``def``. They differ in their scope and calling semantics. 10Whereas ``<%def>`` provides a construct that is very much like a named Python 11``def``, the ``<%block>`` is more layout oriented. 12 13Using Defs 14========== 15 16The ``<%def>`` tag requires a ``name`` attribute, where the ``name`` references 17a Python function signature: 18 19.. sourcecode:: mako 20 21 <%def name="hello()"> 22 hello world 23 </%def> 24 25To invoke the ``<%def>``, it is normally called as an expression: 26 27.. sourcecode:: mako 28 29 the def: ${hello()} 30 31If the ``<%def>`` is not nested inside of another ``<%def>``, 32it's known as a **top level def** and can be accessed anywhere in 33the template, including above where it was defined. 34 35All defs, top level or not, have access to the current 36contextual namespace in exactly the same way their containing 37template does. Suppose the template below is executed with the 38variables ``username`` and ``accountdata`` inside the context: 39 40.. sourcecode:: mako 41 42 Hello there ${username}, how are ya. Lets see what your account says: 43 44 ${account()} 45 46 <%def name="account()"> 47 Account for ${username}:<br/> 48 49 % for row in accountdata: 50 Value: ${row}<br/> 51 % endfor 52 </%def> 53 54The ``username`` and ``accountdata`` variables are present 55within the main template body as well as the body of the 56``account()`` def. 57 58Since defs are just Python functions, you can define and pass 59arguments to them as well: 60 61.. sourcecode:: mako 62 63 ${account(accountname='john')} 64 65 <%def name="account(accountname, type='regular')"> 66 account name: ${accountname}, type: ${type} 67 </%def> 68 69When you declare an argument signature for your def, they are 70required to follow normal Python conventions (i.e., all 71arguments are required except keyword arguments with a default 72value). This is in contrast to using context-level variables, 73which evaluate to ``UNDEFINED`` if you reference a name that 74does not exist. 75 76Calling Defs from Other Files 77----------------------------- 78 79Top level ``<%def>``\ s are **exported** by your template's 80module, and can be called from the outside; including from other 81templates, as well as normal Python code. Calling a ``<%def>`` 82from another template is something like using an ``<%include>`` 83-- except you are calling a specific function within the 84template, not the whole template. 85 86The remote ``<%def>`` call is also a little bit like calling 87functions from other modules in Python. There is an "import" 88step to pull the names from another template into your own 89template; then the function or functions are available. 90 91To import another template, use the ``<%namespace>`` tag: 92 93.. sourcecode:: mako 94 95 <%namespace name="mystuff" file="mystuff.html"/> 96 97The above tag adds a local variable ``mystuff`` to the current 98scope. 99 100Then, just call the defs off of ``mystuff``: 101 102.. sourcecode:: mako 103 104 ${mystuff.somedef(x=5,y=7)} 105 106The ``<%namespace>`` tag also supports some of the other 107semantics of Python's ``import`` statement, including pulling 108names into the local variable space, or using ``*`` to represent 109all names, using the ``import`` attribute: 110 111.. sourcecode:: mako 112 113 <%namespace file="mystuff.html" import="foo, bar"/> 114 115This is just a quick intro to the concept of a **namespace**, 116which is a central Mako concept that has its own chapter in 117these docs. For more detail and examples, see 118:ref:`namespaces_toplevel`. 119 120Calling Defs Programmatically 121----------------------------- 122 123You can call defs programmatically from any :class:`.Template` object 124using the :meth:`~.Template.get_def()` method, which returns a :class:`.DefTemplate` 125object. This is a :class:`.Template` subclass which the parent 126:class:`.Template` creates, and is usable like any other template: 127 128.. sourcecode:: python 129 130 from mako.template import Template 131 132 template = Template(""" 133 <%def name="hi(name)"> 134 hi ${name}! 135 </%def> 136 137 <%def name="bye(name)"> 138 bye ${name}! 139 </%def> 140 """) 141 142 print(template.get_def("hi").render(name="ed")) 143 print(template.get_def("bye").render(name="ed")) 144 145Defs within Defs 146---------------- 147 148The def model follows regular Python rules for closures. 149Declaring ``<%def>`` inside another ``<%def>`` declares it 150within the parent's **enclosing scope**: 151 152.. sourcecode:: mako 153 154 <%def name="mydef()"> 155 <%def name="subdef()"> 156 a sub def 157 </%def> 158 159 i'm the def, and the subcomponent is ${subdef()} 160 </%def> 161 162Just like Python, names that exist outside the inner ``<%def>`` 163exist inside it as well: 164 165.. sourcecode:: mako 166 167 <% 168 x = 12 169 %> 170 <%def name="outer()"> 171 <% 172 y = 15 173 %> 174 <%def name="inner()"> 175 inner, x is ${x}, y is ${y} 176 </%def> 177 178 outer, x is ${x}, y is ${y} 179 </%def> 180 181Assigning to a name inside of a def declares that name as local 182to the scope of that def (again, like Python itself). This means 183the following code will raise an error: 184 185.. sourcecode:: mako 186 187 <% 188 x = 10 189 %> 190 <%def name="somedef()"> 191 ## error ! 192 somedef, x is ${x} 193 <% 194 x = 27 195 %> 196 </%def> 197 198...because the assignment to ``x`` declares ``x`` as local to the 199scope of ``somedef``, rendering the "outer" version unreachable 200in the expression that tries to render it. 201 202.. _defs_with_content: 203 204Calling a Def with Embedded Content and/or Other Defs 205----------------------------------------------------- 206 207A flip-side to def within def is a def call with content. This 208is where you call a def, and at the same time declare a block of 209content (or multiple blocks) that can be used by the def being 210called. The main point of such a call is to create custom, 211nestable tags, just like any other template language's 212custom-tag creation system -- where the external tag controls the 213execution of the nested tags and can communicate state to them. 214Only with Mako, you don't have to use any external Python 215modules, you can define arbitrarily nestable tags right in your 216templates. 217 218To achieve this, the target def is invoked using the form 219``<%namespacename:defname>`` instead of the normal ``${}`` 220syntax. This syntax, introduced in Mako 0.2.3, is functionally 221equivalent to another tag known as ``%call``, which takes the form 222``<%call expr='namespacename.defname(args)'>``. While ``%call`` 223is available in all versions of Mako, the newer style is 224probably more familiar looking. The ``namespace`` portion of the 225call is the name of the **namespace** in which the def is 226defined -- in the most simple cases, this can be ``local`` or 227``self`` to reference the current template's namespace (the 228difference between ``local`` and ``self`` is one of inheritance 229-- see :ref:`namespaces_builtin` for details). 230 231When the target def is invoked, a variable ``caller`` is placed 232in its context which contains another namespace containing the 233body and other defs defined by the caller. The body itself is 234referenced by the method ``body()``. Below, we build a ``%def`` 235that operates upon ``caller.body()`` to invoke the body of the 236custom tag: 237 238.. sourcecode:: mako 239 240 <%def name="buildtable()"> 241 <table> 242 <tr><td> 243 ${caller.body()} 244 </td></tr> 245 </table> 246 </%def> 247 248 <%self:buildtable> 249 I am the table body. 250 </%self:buildtable> 251 252This produces the output (whitespace formatted): 253 254.. sourcecode:: html 255 256 <table> 257 <tr><td> 258 I am the table body. 259 </td></tr> 260 </table> 261 262Using the older ``%call`` syntax looks like: 263 264.. sourcecode:: mako 265 266 <%def name="buildtable()"> 267 <table> 268 <tr><td> 269 ${caller.body()} 270 </td></tr> 271 </table> 272 </%def> 273 274 <%call expr="buildtable()"> 275 I am the table body. 276 </%call> 277 278The ``body()`` can be executed multiple times or not at all. 279This means you can use def-call-with-content to build iterators, 280conditionals, etc: 281 282.. sourcecode:: mako 283 284 <%def name="lister(count)"> 285 % for x in range(count): 286 ${caller.body()} 287 % endfor 288 </%def> 289 290 <%self:lister count="${3}"> 291 hi 292 </%self:lister> 293 294Produces: 295 296.. sourcecode:: html 297 298 hi 299 hi 300 hi 301 302Notice above we pass ``3`` as a Python expression, so that it 303remains as an integer. 304 305A custom "conditional" tag: 306 307.. sourcecode:: mako 308 309 <%def name="conditional(expression)"> 310 % if expression: 311 ${caller.body()} 312 % endif 313 </%def> 314 315 <%self:conditional expression="${4==4}"> 316 i'm the result 317 </%self:conditional> 318 319Produces: 320 321.. sourcecode:: html 322 323 i'm the result 324 325But that's not all. The ``body()`` function also can handle 326arguments, which will augment the local namespace of the body 327callable. The caller must define the arguments which it expects 328to receive from its target def using the ``args`` attribute, 329which is a comma-separated list of argument names. Below, our 330``<%def>`` calls the ``body()`` of its caller, passing in an 331element of data from its argument: 332 333.. sourcecode:: mako 334 335 <%def name="layoutdata(somedata)"> 336 <table> 337 % for item in somedata: 338 <tr> 339 % for col in item: 340 <td>${caller.body(col=col)}</td> 341 % endfor 342 </tr> 343 % endfor 344 </table> 345 </%def> 346 347 <%self:layoutdata somedata="${[[1,2,3],[4,5,6],[7,8,9]]}" args="col">\ 348 Body data: ${col}\ 349 </%self:layoutdata> 350 351Produces: 352 353.. sourcecode:: html 354 355 <table> 356 <tr> 357 <td>Body data: 1</td> 358 <td>Body data: 2</td> 359 <td>Body data: 3</td> 360 </tr> 361 <tr> 362 <td>Body data: 4</td> 363 <td>Body data: 5</td> 364 <td>Body data: 6</td> 365 </tr> 366 <tr> 367 <td>Body data: 7</td> 368 <td>Body data: 8</td> 369 <td>Body data: 9</td> 370 </tr> 371 </table> 372 373You don't have to stick to calling just the ``body()`` function. 374The caller can define any number of callables, allowing the 375``<%call>`` tag to produce whole layouts: 376 377.. sourcecode:: mako 378 379 <%def name="layout()"> 380 ## a layout def 381 <div class="mainlayout"> 382 <div class="header"> 383 ${caller.header()} 384 </div> 385 386 <div class="sidebar"> 387 ${caller.sidebar()} 388 </div> 389 390 <div class="content"> 391 ${caller.body()} 392 </div> 393 </div> 394 </%def> 395 396 ## calls the layout def 397 <%self:layout> 398 <%def name="header()"> 399 I am the header 400 </%def> 401 <%def name="sidebar()"> 402 <ul> 403 <li>sidebar 1</li> 404 <li>sidebar 2</li> 405 </ul> 406 </%def> 407 408 this is the body 409 </%self:layout> 410 411The above layout would produce: 412 413.. sourcecode:: html 414 415 <div class="mainlayout"> 416 <div class="header"> 417 I am the header 418 </div> 419 420 <div class="sidebar"> 421 <ul> 422 <li>sidebar 1</li> 423 <li>sidebar 2</li> 424 </ul> 425 </div> 426 427 <div class="content"> 428 this is the body 429 </div> 430 </div> 431 432The number of things you can do with ``<%call>`` and/or the 433``<%namespacename:defname>`` calling syntax is enormous. You can 434create form widget libraries, such as an enclosing ``<FORM>`` 435tag and nested HTML input elements, or portable wrapping schemes 436using ``<div>`` or other elements. You can create tags that 437interpret rows of data, such as from a database, providing the 438individual columns of each row to a ``body()`` callable which 439lays out the row any way it wants. Basically anything you'd do 440with a "custom tag" or tag library in some other system, Mako 441provides via ``<%def>`` tags and plain Python callables which are 442invoked via ``<%namespacename:defname>`` or ``<%call>``. 443 444.. _blocks: 445 446Using Blocks 447============ 448 449The ``<%block>`` tag introduces some new twists on the 450``<%def>`` tag which make it more closely tailored towards layout. 451 452.. versionadded:: 0.4.1 453 454An example of a block: 455 456.. sourcecode:: mako 457 458 <html> 459 <body> 460 <%block> 461 this is a block. 462 </%block> 463 </body> 464 </html> 465 466In the above example, we define a simple block. The block renders its content in the place 467that it's defined. Since the block is called for us, it doesn't need a name and the above 468is referred to as an **anonymous block**. So the output of the above template will be: 469 470.. sourcecode:: html 471 472 <html> 473 <body> 474 this is a block. 475 </body> 476 </html> 477 478So in fact the above block has absolutely no effect. Its usefulness comes when we start 479using modifiers. Such as, we can apply a filter to our block: 480 481.. sourcecode:: mako 482 483 <html> 484 <body> 485 <%block filter="h"> 486 <html>this is some escaped html.</html> 487 </%block> 488 </body> 489 </html> 490 491or perhaps a caching directive: 492 493.. sourcecode:: mako 494 495 <html> 496 <body> 497 <%block cached="True" cache_timeout="60"> 498 This content will be cached for 60 seconds. 499 </%block> 500 </body> 501 </html> 502 503Blocks also work in iterations, conditionals, just like defs: 504 505.. sourcecode:: mako 506 507 % if some_condition: 508 <%block>condition is met</%block> 509 % endif 510 511While the block renders at the point it is defined in the template, 512the underlying function is present in the generated Python code only 513once, so there's no issue with placing a block inside of a loop or 514similar. Anonymous blocks are defined as closures in the local 515rendering body, so have access to local variable scope: 516 517.. sourcecode:: mako 518 519 % for i in range(1, 4): 520 <%block>i is ${i}</%block> 521 % endfor 522 523Using Named Blocks 524------------------ 525 526Possibly the more important area where blocks are useful is when we 527do actually give them names. Named blocks are tailored to behave 528somewhat closely to Jinja2's block tag, in that they define an area 529of a layout which can be overridden by an inheriting template. In 530sharp contrast to the ``<%def>`` tag, the name given to a block is 531global for the entire template regardless of how deeply it's nested: 532 533.. sourcecode:: mako 534 535 <html> 536 <%block name="header"> 537 <head> 538 <title> 539 <%block name="title">Title</%block> 540 </title> 541 </head> 542 </%block> 543 <body> 544 ${next.body()} 545 </body> 546 </html> 547 548The above example has two named blocks "``header``" and "``title``", both of which can be referred to 549by an inheriting template. A detailed walkthrough of this usage can be found at :ref:`inheritance_toplevel`. 550 551Note above that named blocks don't have any argument declaration the way defs do. They still implement themselves 552as Python functions, however, so they can be invoked additional times beyond their initial definition: 553 554.. sourcecode:: mako 555 556 <div name="page"> 557 <%block name="pagecontrol"> 558 <a href="">previous page</a> | 559 <a href="">next page</a> 560 </%block> 561 562 <table> 563 ## some content 564 </table> 565 566 ${pagecontrol()} 567 </div> 568 569The content referenced by ``pagecontrol`` above will be rendered both above and below the ``<table>`` tags. 570 571To keep things sane, named blocks have restrictions that defs do not: 572 573* The ``<%block>`` declaration cannot have any argument signature. 574* The name of a ``<%block>`` can only be defined once in a template -- an error is raised if two blocks of the same 575 name occur anywhere in a single template, regardless of nesting. A similar error is raised if a top level def 576 shares the same name as that of a block. 577* A named ``<%block>`` cannot be defined within a ``<%def>``, or inside the body of a "call", i.e. 578 ``<%call>`` or ``<%namespacename:defname>`` tag. Anonymous blocks can, however. 579 580Using Page Arguments in Named Blocks 581------------------------------------ 582 583A named block is very much like a top level def. It has a similar 584restriction to these types of defs in that arguments passed to the 585template via the ``<%page>`` tag aren't automatically available. 586Using arguments with the ``<%page>`` tag is described in the section 587:ref:`namespaces_body`, and refers to scenarios such as when the 588``body()`` method of a template is called from an inherited template passing 589arguments, or the template is invoked from an ``<%include>`` tag 590with arguments. To allow a named block to share the same arguments 591passed to the page, the ``args`` attribute can be used: 592 593.. sourcecode:: mako 594 595 <%page args="post"/> 596 597 <a name="${post.title}" /> 598 599 <span class="post_prose"> 600 <%block name="post_prose" args="post"> 601 ${post.content} 602 </%block> 603 </span> 604 605Where above, if the template is called via a directive like 606``<%include file="post.mako" args="post=post" />``, the ``post`` 607variable is available both in the main body as well as the 608``post_prose`` block. 609 610Similarly, the ``**pageargs`` variable is present, in named blocks only, 611for those arguments not explicit in the ``<%page>`` tag: 612 613.. sourcecode:: mako 614 615 <%block name="post_prose"> 616 ${pageargs['post'].content} 617 </%block> 618 619The ``args`` attribute is only allowed with named blocks. With 620anonymous blocks, the Python function is always rendered in the same 621scope as the call itself, so anything available directly outside the 622anonymous block is available inside as well. 623