Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 4. Template Directives > Defining Local Template Blocks

4.3. Defining Local Template Blocks

Sometimes, particularly in a project that involves a large number of small templates, it doesn't seem very efficient to create an external file for every template that you need. The BLOCK ... END construct can be used to avoid this. It allows you to define template component blocks that can be processed with the INCLUDE, PROCESS, and WRAPPER directives.

[% BLOCK tabrow %]
<tr><td>[% name %]<td><td>[% email %]</td></tr>
[% END %]

<table>
[% PROCESS tabrow  name='Fred'  email='fred@nowhere.com' %]
[% PROCESS tabrow  name='Alan'  email='alan@nowhere.com' %]
</table>

A BLOCK definition can be used before it is defined, as long as the definition resides in the same file. The block definition itself does not generate any output.

[% PROCESS tmpblk %]

[% BLOCK tmpblk %] This is OK [% END %]

You can use an anonymous BLOCK to capture the output of a template fragment:

[% julius = BLOCK %]
   And Caesar's spirit, ranging for revenge,
   With Ate by his side come hot from hell,
   Shall in these confines with a monarch's voice
   Cry  'Havoc', and let slip the dogs of war;
   That this foul deed shall smell above the earth
   With carrion men, groaning for burial.
[% END %]

Like a named block, an anonymous block can contain any other template directives that are processed when the block is defined. The output generated by the block is then assigned to the variable julius.

Anonymous BLOCKs can also be used to define block macros. The enclosing block is processed each time the macro is called.

[% MACRO locate BLOCK %]
   The [% animal %] sat on the [% place %].
[% END %]

[% locate(animal='cat', place='mat') %]    # The cat sat on the mat
[% locate(animal='dog', place='log') %]    # The dog sat on the log