Current Path : /usr/share/doc/perl-Template-Toolkit-2.24/manual/ |
Current File : //usr/share/doc/perl-Template-Toolkit-2.24/manual/Directives.html |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN"> <html> <head> <title>Template::Manual::Directives</title> <link rel="stylesheet" type="text/css" href="../css/blue.css" title="Clear Blue"> <link rel="alternate stylesheet" type="text/css" href="../css/orange.css" title="Clear Orange"> <link rel="alternate stylesheet" type="text/css" href="../css/green.css" title="Clear Green"> <link rel="alternate stylesheet" type="text/css" href="../css/purple.css" title="Clear Purple"> <link rel="alternate stylesheet" type="text/css" href="../css/grey.css" title="Clear Grey"> <link rel="alternate stylesheet" type="text/css" href="../css/print.css" title="Print"> <!--[if IE 6]> <link rel="stylesheet" type="text/css" href="../css/ie6.css" /> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="../css/ie7.css" /> <![endif]--> <link rel="stylesheet" type="text/css" href="../css/print.css" media="print"> <script type="text/javascript" src="../js/tt2.js"></script> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <meta name="author" content="Andy Wardley"> </head> <body id="body"> <div id="layout"> <div id="header"> <a href="../index.html" id="logo" alt="" title="Click for the Home Page"><span class="alt">TT2 Home Page</span></a> <ul id="trail"> <li><a href="../manual/index.html">Manual</a></li> <li class="last"><a href="../manual/Directives.html">Directives</a></li> </ul> <div class="controls"> <a href="#" class="menu show" onclick="widescreen_off(); return false" title="Show Menu"> <span class="about">Click to view the menu. It's very nice.</span> </a> <a href="#" class="menu hide" onclick="widescreen_on(); return false" title="Hide Menu"> <span class="about">Click to hide the menu and go all widescreen!</span> </a> <div class="pager"> <a href="../manual/Syntax.html" title="Template::Manual::Syntax" class="go back">Back<span class="about"><h4>Template::Manual::Syntax</h4>Directive syntax, structure and semantics</span></a> <a href="../manual/index.html" title="Template::Manual" class="go up">Up<span class="about"><h4>Template::Manual</h4>Template Toolkit User Manual</span></a> <a href="../manual/Variables.html" title="Template::Manual::Variables" class="go next">Next<span class="about"><h4>Template::Manual::Variables</h4>Template variables and code bindings</span></a> </div> </div> <h1 class="headline">Template::Manual::Directives</h1> <h2 class="subhead">Template directives</h1> </div> <div id="page"> <div id="sidebar"> <a href="../index.html" id="logo"></a> <div id="menu"> <ul class="menu"> <li class="l0 first"><a href="../manual/index.html" class="warm">Manual</a></li> <li class="l1"><a href="../manual/Intro.html">Intro</a></li> <li class="l1"><a href="../manual/Syntax.html">Syntax</a></li> <li class="l1"><a href="../manual/Directives.html" class="warm">Directives</a></li> <li class="l1"><a href="../manual/Variables.html">Variables</a></li> <li class="l1"><a href="../manual/VMethods.html">VMethods</a></li> <li class="l1"><a href="../manual/Config.html">Config</a></li> <li class="l1"><a href="../manual/Filters.html">Filters</a></li> <li class="l1"><a href="../manual/Plugins.html">Plugins</a></li> <li class="l1"><a href="../manual/Internals.html">Internals</a></li> <li class="l1"><a href="../manual/Views.html">Views</a></li> <li class="l1"><a href="../manual/Credits.html">Credits</a></li> <li class="l0"><a href="../modules/index.html">Modules</a></li> <li class="l0"><a href="../tools/index.html">Tools</a></li> <li class="l0"><a href="../tutorial/index.html">Tutorial</a></li> <li class="l0 last"><a href="../faq/index.html">FAQ</a></li> </ul> <div class="foot"></div> </div> </div> <div id="content"> <div class="section"> <div class="head"> <h1 id="contents" onclick="switch_section(this)" title="Click title to show/hide section content.">Contents</h1> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <ul class="toc"> <li class=""><a href="#Accessing_and_Updating_Template_Variables">Accessing and Updating Template Variables</a></li> <li class="sub"><a href="#section_GET">GET</a></li> <li class="sub"><a href="#section_CALL">CALL</a></li> <li class="sub"><a href="#section_SET">SET</a></li> <li class="sub"><a href="#section_DEFAULT">DEFAULT</a></li> <li class=""><a href="#Processing_Template_Files_and_Blocks">Processing Template Files and Blocks</a></li> <li class="sub"><a href="#section_INSERT">INSERT</a></li> <li class="sub"><a href="#section_INCLUDE">INCLUDE</a></li> <li class="sub"><a href="#section_PROCESS">PROCESS</a></li> <li class="sub"><a href="#section_WRAPPER">WRAPPER</a></li> <li class="sub"><a href="#section_BLOCK">BLOCK</a></li> <li class=""><a href="#Conditional_Processing">Conditional Processing</a></li> <li class="sub"><a href="#section_IF_UNLESS_ELSIF_ELSE">IF / UNLESS / ELSIF / ELSE</a></li> <li class="sub"><a href="#section_SWITCH_CASE">SWITCH / CASE</a></li> <li class=""><a href="#Loop_Processing">Loop Processing</a></li> <li class="sub"><a href="#section_FOREACH">FOREACH</a></li> <li class="sub"><a href="#section_WHILE">WHILE</a></li> <li class=""><a href="#Filters_Plugins_Macros_and_Perl">Filters, Plugins, Macros and Perl</a></li> <li class="sub"><a href="#section_FILTER">FILTER</a></li> <li class="sub"><a href="#section_USE">USE</a></li> <li class="sub"><a href="#section_MACRO">MACRO</a></li> <li class="sub"><a href="#section_PERL">PERL</a></li> <li class="sub"><a href="#section_RAWPERL">RAWPERL</a></li> <li class=""><a href="#Exception_Handling_and_Flow_Control">Exception Handling and Flow Control</a></li> <li class="sub"><a href="#section_TRY_THROW_CATCH_FINAL">TRY / THROW / CATCH / FINAL</a></li> <li class="sub"><a href="#section_NEXT">NEXT</a></li> <li class="sub"><a href="#section_LAST">LAST</a></li> <li class="sub"><a href="#section_RETURN">RETURN</a></li> <li class="sub"><a href="#section_STOP">STOP</a></li> <li class="sub"><a href="#section_CLEAR">CLEAR</a></li> <li class=""><a href="#Miscellaneous">Miscellaneous</a></li> <li class="sub"><a href="#section_META">META</a></li> <li class="sub"><a href="#section_TAGS">TAGS</a></li> <li class="sub"><a href="#section_DEBUG">DEBUG</a></li> </ul> </div> </div> <div class="pod"> <div class="section"> <div class="head"> <h1 id="Accessing_and_Updating_Template_Variables" onclick="switch_section(this)" title="Click title to show/hide section content.">Accessing and Updating Template Variables</h1> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <div class="subsection"> <div class="head"> <h2 id="section_GET" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">GET</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>GET</code> directive retrieves and outputs the value of the named variable. </p> <pre><span class="tt">[% GET foo %]</span></pre> <p> The <code>GET</code> keyword is optional. A variable can be specified in a directive tag by itself. </p> <pre><span class="tt">[% foo %]</span></pre> <p> The variable can have an unlimited number of elements, each separated by a dot. Each element can have arguments specified within parentheses. </p> <pre><span class="tt">[% foo %]</span> <span class="tt">[% bar.baz %]</span> <span class="tt">[% biz.baz(10) %]</span> ...etc...</pre> <p> See <a href="../manual/Variables.html">Template::Manual::Variables</a> for a full discussion on template variables. </p> <p> You can also specify expressions using the logical (<code>and</code>, <code>or</code>, <code>not</code>, <code>?</code>, <code>:</code>) and mathematic operators (<code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>%</code>, <code>mod</code>, <code>div</code>). </p> <pre><span class="tt">[% template.title or default.title %]</span> <span class="tt">[% score * 100 %]</span> <span class="tt">[% order.nitems ? checkout(order.total) : 'no items' %]</span></pre> <p> The <code>div</code> operator returns the integer result of division. Both <code>%</code> and <code>mod</code> return the modulus (i.e. remainder) of division. </p> <pre><span class="tt">[% 15 / 6 %]</span> # 2.5 <span class="tt">[% 15 div 6 %]</span> # 2 <span class="tt">[% 15 mod 6 %]</span> # 3</pre> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_CALL" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">CALL</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>CALL</code> directive is similar to <code>GET</code> in evaluating the variable named, but doesn't print the result returned. This can be useful when a variable is bound to a sub-routine or object method which you want to call but aren't interested in the value returned. </p> <pre><span class="tt">[% CALL dbi.disconnect %]</span> <span class="tt">[% CALL inc_page_counter(page_count) %]</span></pre> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_SET" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">SET</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>SET</code> directive allows you to assign new values to existing variables or create new temporary variables. </p> <pre><span class="tt">[% SET title = 'Hello World' %]</span></pre> <p> The <code>SET</code> keyword is also optional. </p> <pre><span class="tt">[% title = 'Hello World' %]</span></pre> <p> Variables may be assigned the values of other variables, unquoted numbers (2.718), literal text ('single quotes') or quoted text ("double quotes"). In the latter case, any variable references within the text will be interpolated when the string is evaluated. Variables should be prefixed by <code>$</code>, using curly braces to explicitly scope the variable name where necessary. </p> <pre><span class="tt">[% foo = 'Foo' %]</span> # literal value 'Foo' <span class="tt">[% bar = foo %]</span> # value of variable 'foo' <span class="tt">[% cost = '$100' %]</span> # literal value '$100' <span class="tt">[% item = "$bar: ${cost}.00" %]</span> # value "Foo: $100.00"</pre> <p> Multiple variables may be assigned in the same directive and are evaluated in the order specified. Thus, the above could have been written: </p> <pre><span class="tt">[% foo = 'Foo' bar = foo cost = '$100' item = "$bar: ${cost}.00" %]</span></pre> <p> Simple expressions can also be used, as per <code>GET</code>. </p> <pre><span class="tt">[% ten = 10 twenty = 20 thirty = twenty + ten forty = 2 * twenty fifty = 100 div 2 six = twenty mod 7 %]</span></pre> <p> You can concatenate strings together using the <code>' _ '</code> operator. In Perl 5, the <code>.</code> is used for string concatenation, but in Perl 6, as in the Template Toolkit, the <code>.</code> will be used as the method calling operator and <code>' _ '</code> will be used for string concatenation. Note that the operator must be specified with surrounding whitespace which, as Larry says, is construed as a feature: </p> <pre><span class="tt">[% copyright = '(C) Copyright' _ year _ ' ' _ author %]</span></pre> <p> You can, of course, achieve a similar effect with double quoted string interpolation. </p> <pre><span class="tt">[% copyright = "(C) Copyright $year $author" %]</span></pre> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_DEFAULT" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">DEFAULT</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>DEFAULT</code> directive is similar to <code>SET</code> but only updates variables that are currently undefined or have no "true" value (in the Perl sense). </p> <pre><span class="tt">[% DEFAULT name = 'John Doe' id = 'jdoe' %]</span></pre> <p> This can be particularly useful in common template components to ensure that some sensible default are provided for otherwise undefined variables. </p> <pre><span class="tt">[% DEFAULT title = 'Hello World' bgcol = '#ffffff' %]</span> <html> <head> <title><span class="tt">[% title %]</span></title> </head> <body bgcolor="<span class="tt">[% bgcol %]</span>"> ...etc...</pre> </div> </div> </div> </div> <div class="section"> <div class="head"> <h1 id="Processing_Template_Files_and_Blocks" onclick="switch_section(this)" title="Click title to show/hide section content.">Processing Template Files and Blocks</h1> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <div class="subsection"> <div class="head"> <h2 id="section_INSERT" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">INSERT</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>INSERT</code> directive is used to insert the contents of an external file at the current position. </p> <pre><span class="tt">[% INSERT myfile %]</span></pre> <p> No attempt to parse or process the file is made. The contents, possibly including any embedded template directives, are inserted intact. </p> <p> The filename specified should be relative to one of the <code>INCLUDE_PATH</code> directories. Absolute (i.e. starting with <code>/</code>) and relative (i.e. starting with <code>.</code>) filenames may be used if the <code>ABSOLUTE</code> and <code>RELATIVE</code> options are set, respectively. Both these options are disabled by default. </p> <pre>my $template = Template->new({ INCLUDE_PATH => '/here:/there', }); $template->process('myfile');</pre> <p> <i>myfile</i>: </p> <pre><span class="tt">[% INSERT foo %]</span> # looks for /here/foo then /there/foo <span class="tt">[% INSERT /etc/passwd %]</span> # file error: ABSOLUTE not set <span class="tt">[% INSERT ../secret %]</span> # file error: RELATIVE not set</pre> <p> For convenience, the filename does not need to be quoted as long as it contains only alphanumeric characters, underscores, dots or forward slashes. Names containing any other characters should be quoted. </p> <pre><span class="tt">[% INSERT misc/legalese.txt %]</span> <span class="tt">[% INSERT 'dos98/Program Files/stupid' %]</span></pre> <p> To evaluate a variable to specify a filename, you should explicitly prefix it with a <code>$</code> or use double-quoted string interpolation. </p> <pre><span class="tt">[% language = 'en' legalese = 'misc/legalese.txt' %]</span> <span class="tt">[% INSERT $legalese %]</span> # misc/legalese.txt <span class="tt">[% INSERT "$language/$legalese" %]</span> # en/misc/legalese.txt</pre> <p> Multiple files can be specified using <code>+</code> as a delimiter. All files should be unquoted names or quoted strings. Any variables should be interpolated into double-quoted strings. </p> <pre><span class="tt">[% INSERT legalese.txt + warning.txt %]</span> <span class="tt">[% INSERT "$legalese" + warning.txt %]</span> # requires quoting</pre> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_INCLUDE" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">INCLUDE</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>INCLUDE</code> directive is used to process and include the output of another template file or block. </p> <pre><span class="tt">[% INCLUDE header %]</span></pre> <p> If a <code>BLOCK</code> of the specified name is defined in the same file, or in a file from which the current template has been called (i.e. a parent template) then it will be used in preference to any file of the same name. </p> <pre><span class="tt">[% INCLUDE table %]</span> # uses BLOCK defined below <span class="tt">[% BLOCK table %]</span> <table> ... </table> <span class="tt">[% END %]</span></pre> <p> If a <code>BLOCK</code> definition is not currently visible then the template name should be a file relative to one of the <code>INCLUDE_PATH</code> directories, or an absolute or relative file name if the <code>ABSOLUTE</code>/<code>RELATIVE</code> options are appropriately enabled. The <code>INCLUDE</code> directive automatically quotes the filename specified, as per <code>INSERT</code> described above. When a variable contains the name of the template for the <code>INCLUDE</code> directive, it should be explicitly prefixed by <code>$</code> or double-quoted </p> <pre><span class="tt">[% myheader = 'my/misc/header' %]</span> <span class="tt">[% INCLUDE myheader %]</span> # 'myheader' <span class="tt">[% INCLUDE $myheader %]</span> # 'my/misc/header' <span class="tt">[% INCLUDE "$myheader" %]</span> # 'my/misc/header'</pre> <p> Any template directives embedded within the file will be processed accordingly. All variables currently defined will be visible and accessible from within the included template. </p> <pre><span class="tt">[% title = 'Hello World' %]</span> <span class="tt">[% INCLUDE header %]</span> <body> ...</pre> <p> <i>header</i>: </p> <pre><html> <title><span class="tt">[% title %]</span></title></pre> <p> output: </p> <pre><html> <title>Hello World</title> <body> ...</pre> <p> Local variable definitions may be specified after the template name, temporarily masking any existing variables. Insignificant whitespace is ignored within directives so you can add variable definitions on the same line, the next line or split across several line with comments interspersed, if you prefer. </p> <pre><span class="tt">[% INCLUDE table %]</span> <span class="tt">[% INCLUDE table title="Active Projects" %]</span> <span class="tt">[% INCLUDE table title = "Active Projects" bgcolor = "#80ff00" # chartreuse border = 2 %]</span></pre> <p> The <code>INCLUDE</code> directive localises (i.e. copies) all variables before processing the template. Any changes made within the included template will not affect variables in the including template. </p> <pre><span class="tt">[% foo = 10 %]</span> foo is originally <span class="tt">[% foo %]</span> <span class="tt">[% INCLUDE bar %]</span> foo is still <span class="tt">[% foo %]</span> <span class="tt">[% BLOCK bar %]</span> foo was <span class="tt">[% foo %]</span> <span class="tt">[% foo = 20 %]</span> foo is now <span class="tt">[% foo %]</span> <span class="tt">[% END %]</span></pre> <p> output: </p> <pre>foo is originally 10 foo was 10 foo is now 20 foo is still 10</pre> <p> Technical Note: the localisation of the stash (that is, the process by which variables are copied before an <code>INCLUDE</code> to prevent being overwritten) is only skin deep. The top-level variable namespace (hash) is copied, but no attempt is made to perform a deep-copy of other structures (hashes, arrays, objects, etc.) Therefore, a <code>foo</code> variable referencing a hash will be copied to create a new <code>foo</code> variable but which points to the same hash array. Thus, if you update compound variables (e.g. <code>foo.bar</code>) then you will change the original copy, regardless of any stash localisation. If you're not worried about preserving variable values, or you trust the templates you're including then you might prefer to use the <code>PROCESS</code> directive which is faster by virtue of not performing any localisation. </p> <p> You can specify dotted variables as "local" variables to an <code>INCLUDE</code> directive. However, be aware that because of the localisation issues explained above (if you skipped the previous Technical Note above then you might want to go back and read it or skip this section too), the variables might not actualy be "local". If the first element of the variable name already references a hash array then the variable update will affect the original variable. </p> <pre><span class="tt">[% foo = { bar = 'Baz' } %]</span> <span class="tt">[% INCLUDE somefile foo.bar='Boz' %]</span> <span class="tt">[% foo.bar %]</span> # Boz</pre> <p> This behaviour can be a little unpredictable (and may well be improved upon in a future version). If you know what you're doing with it and you're sure that the variables in question are defined (nor not) as you expect them to be, then you can rely on this feature to implement some powerful "global" data sharing techniques. Otherwise, you might prefer to steer well clear and always pass simple (undotted) variables as parameters to <code>INCLUDE</code> and other similar directives. </p> <p> If you want to process several templates in one go then you can specify each of their names (quoted or unquoted names only, no unquoted <code>$variables</code>) joined together by <code>+</code>. The <code>INCLUDE</code> directive will then process them in order. </p> <pre><span class="tt">[% INCLUDE html/header + "site/$header" + site/menu title = "My Groovy Web Site" %]</span></pre> <p> The variable stash is localised once and then the templates specified are processed in order, all within that same variable context. This makes it slightly faster than specifying several separate <code>INCLUDE</code> directives (because you only clone the variable stash once instead of n times), but not quite as "safe" because any variable changes in the first file will be visible in the second, third and so on. This might be what you want, of course, but then again, it might not. </p> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_PROCESS" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">PROCESS</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The PROCESS directive is similar to <code>INCLUDE</code> but does not perform any localisation of variables before processing the template. Any changes made to variables within the included template will be visible in the including template. </p> <pre><span class="tt">[% foo = 10 %]</span> foo is <span class="tt">[% foo %]</span> <span class="tt">[% PROCESS bar %]</span> foo is <span class="tt">[% foo %]</span> <span class="tt">[% BLOCK bar %]</span> <span class="tt">[% foo = 20 %]</span> changed foo to <span class="tt">[% foo %]</span> <span class="tt">[% END %]</span></pre> <p> output: </p> <pre>foo is 10 changed foo to 20 foo is 20</pre> <p> Parameters may be specified in the <code>PROCESS</code> directive, but these too will become visible changes to current variable values. </p> <pre><span class="tt">[% foo = 10 %]</span> foo is <span class="tt">[% foo %]</span> <span class="tt">[% PROCESS bar foo = 20 %]</span> foo is <span class="tt">[% foo %]</span> <span class="tt">[% BLOCK bar %]</span> this is bar, foo is <span class="tt">[% foo %]</span> <span class="tt">[% END %]</span></pre> <p> output: </p> <pre>foo is 10 this is bar, foo is 20 foo is 20</pre> <p> The <code>PROCESS</code> directive is slightly faster than <code>INCLUDE</code> because it avoids the need to localise (i.e. copy) the variable stash before processing the template. As with <code>INSERT</code> and <code>INCLUDE</code>, the first parameter does not need to be quoted as long as it contains only alphanumeric characters, underscores, periods or forward slashes. A <code>$</code> prefix can be used to explicitly indicate a variable which should be interpolated to provide the template name: </p> <pre><span class="tt">[% myheader = 'my/misc/header' %]</span> <span class="tt">[% PROCESS myheader %]</span> # 'myheader' <span class="tt">[% PROCESS $myheader %]</span> # 'my/misc/header'</pre> <p> As with <code>INCLUDE</code>, multiple templates can be specified, delimited by <code>+</code>, and are processed in order. </p> <pre><span class="tt">[% PROCESS html/header + my/header %]</span></pre> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_WRAPPER" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">WRAPPER</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> It's not unusual to find yourself adding common headers and footers to pages or sub-sections within a page. Something like this: </p> <pre><span class="tt">[% INCLUDE section/header title = 'Quantum Mechanics' %]</span> Quantum mechanics is a very interesting subject wish should prove easy for the layman to fully comprehend. <span class="tt">[% INCLUDE section/footer %]</span> <span class="tt">[% INCLUDE section/header title = 'Desktop Nuclear Fusion for under $50' %]</span> This describes a simple device which generates significant sustainable electrical power from common tap water by process of nuclear fusion. <span class="tt">[% INCLUDE section/footer %]</span></pre> <p> The individual template components being included might look like these: </p> <p> section/header: </p> <pre><p> <h2><span class="tt">[% title %]</span></h2></pre> <p> section/footer: </p> <pre></p></pre> <p> The <code>WRAPPER</code> directive provides a way of simplifying this a little. It encloses a block up to a matching <code>END</code> directive, which is first processed to generate some output. This is then passed to the named template file or <code>BLOCK</code> as the <code>content</code> variable. </p> <pre><span class="tt">[% WRAPPER section title = 'Quantum Mechanics' %]</span> Quantum mechanics is a very interesting subject wish should prove easy for the layman to fully comprehend. <span class="tt">[% END %]</span> <span class="tt">[% WRAPPER section title = 'Desktop Nuclear Fusion for under $50' %]</span> This describes a simple device which generates significant sustainable electrical power from common tap water by process of nuclear fusion. <span class="tt">[% END %]</span></pre> <p> The single 'section' template can then be defined as: </p> <pre><h2><span class="tt">[% title %]</span></h2> <p> <span class="tt">[% content %]</span> </p></pre> <p> Like other block directives, it can be used in side-effect notation: </p> <pre><span class="tt">[% INSERT legalese.txt WRAPPER big_bold_table %]</span></pre> <p> It's also possible to specify multiple templates to a <code>WRAPPER</code> directive. The specification order indicates outermost to innermost wrapper templates. For example, given the following template block definitions: </p> <pre><span class="tt">[% BLOCK bold %]</span><b><span class="tt">[% content %]</span></b><span class="tt">[% END %]</span> <span class="tt">[% BLOCK italic %]</span><i><span class="tt">[% content %]</span></i><span class="tt">[% END %]</span></pre> <p> the directive </p> <pre><span class="tt">[% WRAPPER bold+italic %]</span>Hello World<span class="tt">[% END %]</span></pre> <p> would generate the following output: </p> <pre><b><i>Hello World</i></b></pre> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_BLOCK" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">BLOCK</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>BLOCK</code>...<code>END</code> construct can be used to define template component blocks which can be processed with the <code>INCLUDE</code>, <code>PROCESS</code> and <code>WRAPPER</code> directives. </p> <pre><span class="tt">[% BLOCK tabrow %]</span> <tr> <td><span class="tt">[% name %]</span><td> <td><span class="tt">[% email %]</span></td> </tr> <span class="tt">[% END %]</span> <table> <span class="tt">[% PROCESS tabrow name='Fred' email='fred@nowhere.com' %]</span> <span class="tt">[% PROCESS tabrow name='Alan' email='alan@nowhere.com' %]</span> </table></pre> <p> A <code>BLOCK</code> 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. </p> <pre><span class="tt">[% PROCESS tmpblk %]</span> <span class="tt">[% BLOCK tmpblk %]</span> This is OK <span class="tt">[% END %]</span></pre> <p> You can use an anonymous <code>BLOCK</code> to capture the output of a template fragment. </p> <pre><span class="tt">[% julius = BLOCK %]</span> 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. <span class="tt">[% END %]</span></pre> <p> Like a named block, it can contain any other template directives which are processed when the block is defined. The output generated by the block is then assigned to the variable <code>julius</code>. </p> <p> Anonymous <code>BLOCK</code>s can also be used to define block macros. The enclosing block is processed each time the macro is called. </p> <pre><span class="tt">[% MACRO locate BLOCK %]</span> The <span class="tt">[% animal %]</span> sat on the <span class="tt">[% place %]</span>. <span class="tt">[% END %]</span> <span class="tt">[% locate(animal='cat', place='mat') %]</span> # The cat sat on the mat <span class="tt">[% locate(animal='dog', place='log') %]</span> # The dog sat on the log</pre> </div> </div> </div> </div> <div class="section"> <div class="head"> <h1 id="Conditional_Processing" onclick="switch_section(this)" title="Click title to show/hide section content.">Conditional Processing</h1> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <div class="subsection"> <div class="head"> <h2 id="section_IF_UNLESS_ELSIF_ELSE" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">IF / UNLESS / ELSIF / ELSE</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>IF</code> and <code>UNLESS</code> directives can be used to process or ignore a block based on some run-time condition. </p> <pre><span class="tt">[% IF frames %]</span> <span class="tt">[% INCLUDE frameset %]</span> <span class="tt">[% END %]</span> <span class="tt">[% UNLESS text_mode %]</span> <span class="tt">[% INCLUDE biglogo %]</span> <span class="tt">[% END %]</span></pre> <p> Multiple conditions may be joined with <code>ELSIF</code> and/or <code>ELSE</code> blocks. </p> <pre><span class="tt">[% IF age < 10 %]</span> Hello <span class="tt">[% name %]</span>, does your mother know you're using her AOL account? <span class="tt">[% ELSIF age < 18 %]</span> Sorry, you're not old enough to enter (and too dumb to lie about your age) <span class="tt">[% ELSE %]</span> Welcome <span class="tt">[% name %]</span>. <span class="tt">[% END %]</span></pre> <p> The following conditional and boolean operators may be used: </p> <pre>== != < <= > >= && || ! and or not</pre> <p> Conditions may be arbitrarily complex and are evaluated with the same precedence as in Perl. Parenthesis may be used to explicitly determine evaluation order. </p> <pre># ridiculously contrived complex example <span class="tt">[% IF (name == 'admin' || uid <= 0) && mode == 'debug' %]</span> I'm confused. <span class="tt">[% ELSIF more > less %]</span> That's more or less correct. <span class="tt">[% END %]</span></pre> <p> The <code>and</code>, <code>or</code> and <code>not</code> operator are provided as aliases for <code>&&</code>, <code>||</code> and <code>!</code>, respectively. Unlike Perl, which treats <code>and</code>, <code>or</code> and <code>not</code> as separate, lower-precedence versions of the other operators, the Template Toolkit performs a straightforward substitution of <code>and</code> for <code>&&</code>, and so on. That means that <code>and</code>, <code>or</code> and <code>not</code> have the same operator precedence as <code>&&</code>, <code>||</code> and <code>!</code>. </p> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_SWITCH_CASE" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">SWITCH / CASE</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>SWITCH</code> / <code>CASE</code> construct can be used to perform a multi-way conditional test. The <code>SWITCH</code> directive expects an expression which is first evaluated and then compared against each CASE statement in turn. Each <code>CASE</code> directive should contain a single value or a list of values which should match. <code>CASE</code> may also be left blank or written as <code>[% CASE DEFAULT %]</code> to specify a default match. Only one <code>CASE</code> matches, there is no drop-through between <code>CASE</code> statements. </p> <pre><span class="tt">[% SWITCH myvar %]</span> <span class="tt">[% CASE 'value1' %]</span> ... <span class="tt">[% CASE ['value2', 'value3'] %]</span> # multiple values ... <span class="tt">[% CASE myhash.keys %]</span> # ditto ... <span class="tt">[% CASE %]</span> # default ... <span class="tt">[% END %]</span></pre> </div> </div> </div> </div> <div class="section"> <div class="head"> <h1 id="Loop_Processing" onclick="switch_section(this)" title="Click title to show/hide section content.">Loop Processing</h1> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <div class="subsection"> <div class="head"> <h2 id="section_FOREACH" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">FOREACH</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>FOREACH</code> directive will iterate through the items in a list, processing the enclosed block for each one. </p> <pre><span class="tt">[% foo = 'Foo' items = [ 'one', 'two', 'three' ] %]</span> Things: <span class="tt">[% FOREACH thing IN [ foo 'Bar' "$foo Baz" ] %]</span> * <span class="tt">[% thing %]</span> <span class="tt">[% END %]</span> Items: <span class="tt">[% FOREACH i IN items %]</span> * <span class="tt">[% i %]</span> <span class="tt">[% END %]</span> Stuff: <span class="tt">[% stuff = [ foo "$foo Bar" ] %]</span> <span class="tt">[% FOREACH s IN stuff %]</span> * <span class="tt">[% s %]</span> <span class="tt">[% END %]</span></pre> <p> output: </p> <pre>Things: * Foo * Bar * Foo Baz Items: * one * two * three Stuff: * Foo * Foo Bar</pre> <p> You can use also use <code>=</code> instead of <code>IN</code> if you prefer. </p> <pre><span class="tt">[% FOREACH i = items %]</span></pre> <p> When the <code>FOREACH</code> directive is used without specifying a target variable, any iterated values which are hash references will be automatically imported. </p> <pre><span class="tt">[% userlist = [ { id => 'tom', name => 'Thomas' }, { id => 'dick', name => 'Richard' }, { id => 'larry', name => 'Lawrence' }, ] %]</span> <span class="tt">[% FOREACH user IN userlist %]</span> <span class="tt">[% user.id %]</span> <span class="tt">[% user.name %]</span> <span class="tt">[% END %]</span></pre> <p> short form: </p> <pre><span class="tt">[% FOREACH userlist %]</span> <span class="tt">[% id %]</span> <span class="tt">[% name %]</span> <span class="tt">[% END %]</span></pre> <p> Note that this particular usage creates a localised variable context to prevent the imported hash keys from overwriting any existing variables. The imported definitions and any other variables defined in such a <code>FOREACH</code> loop will be lost at the end of the loop, when the previous context and variable values are restored. </p> <p> However, under normal operation, the loop variable remains in scope after the <code>FOREACH</code> loop has ended (caveat: overwriting any variable previously in scope). This is useful as the loop variable is secretly an iterator object (see below) and can be used to analyse the last entry processed by the loop. </p> <p> The <code>FOREACH</code> directive can also be used to iterate through the entries in a hash array. Each entry in the hash is returned in sorted order (based on the key) as a hash array containing 'key' and 'value' items. </p> <pre><span class="tt">[% users = { tom => 'Thomas', dick => 'Richard', larry => 'Lawrence', } %]</span> <span class="tt">[% FOREACH u IN users %]</span> * <span class="tt">[% u.key %]</span> : <span class="tt">[% u.value %]</span> <span class="tt">[% END %]</span></pre> <p> Output: </p> <pre>* dick : Richard * larry : Lawrence * tom : Thomas</pre> <p> The <code>NEXT</code> directive starts the next iteration in the <code>FOREACH</code> loop. </p> <pre><span class="tt">[% FOREACH user IN userlist %]</span> <span class="tt">[% NEXT IF user.isguest %]</span> Name: <span class="tt">[% user.name %]</span> Email: <span class="tt">[% user.email %]</span> <span class="tt">[% END %]</span></pre> <p> The <code>LAST</code> directive can be used to prematurely exit the loop. <code>BREAK</code> is also provided as an alias for <code>LAST</code>. </p> <pre><span class="tt">[% FOREACH match IN results.nsort('score').reverse %]</span> <span class="tt">[% LAST IF match.score < 50 %]</span> <span class="tt">[% match.score %]</span> : <span class="tt">[% match.url %]</span> <span class="tt">[% END %]</span></pre> <p> The <code>FOREACH</code> directive is implemented using the <a href="../modules/Template/Iterator.html">Template::Iterator</a> module. A reference to the iterator object for a <code>FOREACH</code> directive is implicitly available in the <code>loop</code> variable. The following methods can be called on the <code>loop</code> iterator. </p> <pre>size() number of elements in the list max() index number of last element (size - 1) index() index of current iteration from 0 to max() count() iteration counter from 1 to size() (i.e. index() + 1) first() true if the current iteration is the first last() true if the current iteration is the last prev() return the previous item in the list next() return the next item in the list</pre> <p> See <a href="../modules/Template/Iterator.html">Template::Iterator</a> for further details. </p> <p> Example: </p> <pre><span class="tt">[% FOREACH item IN [ 'foo', 'bar', 'baz' ] -%]</span> <span class="tt">[%- "<ul>\n" IF loop.first %]</span> <li><span class="tt">[% loop.count %]</span>/<span class="tt">[% loop.size %]</span>: <span class="tt">[% item %]</span> <span class="tt">[%- "</ul>\n" IF loop.last %]</span> <span class="tt">[% END %]</span></pre> <p> Output: </p> <pre><ul> <li>1/3: foo <li>2/3: bar <li>3/3: baz </ul></pre> <p> Nested loops will work as expected, with the <code>loop</code> variable correctly referencing the innermost loop and being restored to any previous value (i.e. an outer loop) at the end of the loop. </p> <pre><span class="tt">[% FOREACH group IN grouplist; # loop => group iterator "Groups:\n" IF loop.first; FOREACH user IN group.userlist; # loop => user iterator "$loop.count: $user.name\n"; END; # loop => group iterator "End of Groups\n" IF loop.last; END %]</span></pre> <p> The <code>iterator</code> plugin can also be used to explicitly create an iterator object. This can be useful within nested loops where you need to keep a reference to the outer iterator within the inner loop. The iterator plugin effectively allows you to create an iterator by a name other than <code>loop</code>. See <a href="../modules/Template/Plugin/Iterator.html">Template::Plugin::Iterator</a> for further details. </p> <pre><span class="tt">[% USE giter = iterator(grouplist) %]</span> <span class="tt">[% FOREACH group IN giter %]</span> <span class="tt">[% FOREACH user IN group.userlist %]</span> user #<span class="tt">[% loop.count %]</span> in group <span class="tt">[% giter.count %]</span> is named <span class="tt">[% user.name %]</span> <span class="tt">[% END %]</span> <span class="tt">[% END %]</span></pre> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_WHILE" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">WHILE</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>WHILE</code> directive can be used to repeatedly process a template block while a conditional expression evaluates true. The expression may be arbitrarily complex as per <code>IF</code> / <code>UNLESS</code>. </p> <pre><span class="tt">[% WHILE total < 100 %]</span> ... <span class="tt">[% total = calculate_new_total %]</span> <span class="tt">[% END %]</span></pre> <p> An assignment can be enclosed in parenthesis to evaluate the assigned value. </p> <pre><span class="tt">[% WHILE (user = get_next_user_record) %]</span> <span class="tt">[% user.name %]</span> <span class="tt">[% END %]</span></pre> <p> The <code>NEXT</code> directive can be used to start the next iteration of a <code>WHILE</code> loop and <code>BREAK</code> can be used to exit the loop, both as per <code>FOREACH</code>. </p> <p> The Template Toolkit uses a failsafe counter to prevent runaway <code>WHILE</code> loops which would otherwise never terminate. If the loop exceeds 1000 iterations then an <code>undef</code> exception will be thrown, reporting the error: </p> <pre>WHILE loop terminated (> 1000 iterations)</pre> <p> The <code>$Template::Directive::WHILE_MAX</code> variable controls this behaviour and can be set to a higher value if necessary. </p> </div> </div> </div> </div> <div class="section"> <div class="head"> <h1 id="Filters_Plugins_Macros_and_Perl" onclick="switch_section(this)" title="Click title to show/hide section content.">Filters, Plugins, Macros and Perl</h1> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <div class="subsection"> <div class="head"> <h2 id="section_FILTER" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">FILTER</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>FILTER</code> directive can be used to post-process the output of a block. A number of standard filters are provided with the Template Toolkit. The <code>html</code> filter, for example, escapes the '<', '>' and '&' characters to prevent them from being interpreted as HTML tags or entity reference markers. </p> <pre><span class="tt">[% FILTER html %]</span> HTML text may have < and > characters embedded which you want converted to the correct HTML entities. <span class="tt">[% END %]</span></pre> <p> output: </p> <pre>HTML text may have &lt; and &gt; characters embedded which you want converted to the correct HTML entities.</pre> <p> The <code>FILTER</code> directive can also follow various other non-block directives. For example: </p> <pre><span class="tt">[% INCLUDE mytext FILTER html %]</span></pre> <p> The <code>|</code> character can also be used as an alias for <code>FILTER</code>. </p> <pre><span class="tt">[% INCLUDE mytext | html %]</span></pre> <p> Multiple filters can be chained together and will be called in sequence. </p> <pre><span class="tt">[% INCLUDE mytext FILTER html FILTER html_para %]</span></pre> <p> or </p> <pre><span class="tt">[% INCLUDE mytext | html | html_para %]</span></pre> <p> Filters come in two flavours, known as 'static' or 'dynamic'. A static filter is a simple subroutine which accepts a text string as the only argument and returns the modified text. The <code>html</code> filter is an example of a static filter, implemented as: </p> <pre>sub html_filter { my $text = shift; for ($text) { s/&/&amp;/g; s/</&lt;/g; s/>/&gt;/g; } return $text; }</pre> <p> Dynamic filters can accept arguments which are specified when the filter is called from a template. The <code>repeat</code> filter is such an example, accepting a numerical argument which specifies the number of times that the input text should be repeated. </p> <pre><span class="tt">[% FILTER repeat(3) %]</span>blah <span class="tt">[% END %]</span></pre> <p> output: </p> <pre>blah blah blah</pre> <p> These are implemented as filter 'factories'. The factory subroutine is passed a reference to the current <a href="../modules/Template/Context.html">Template::Context</a> object along with any additional arguments specified. It should then return a subroutine reference (e.g. a closure) which implements the filter. The <code>repeat</code> filter factory is implemented like this: </p> <pre>sub repeat_filter_factory { my ($context, $iter) = @_; $iter = 1 unless defined $iter; return sub { my $text = shift; $text = '' unless defined $text; return join('\n', $text) x $iter; } }</pre> <p> The <code>FILTERS</code> option, described in <a href="../manual/Config.html">Template::Manual::Config</a>, allows custom filters to be defined when a Template object is instantiated. The <a href="../modules/Template/Context.html#method_define_filter">define_filter()</a> method allows further filters to be defined at any time. </p> <p> When using a filter, it is possible to assign an alias to it for further use. This is most useful for dynamic filters that you want to re-use with the same configuration. </p> <pre><span class="tt">[% FILTER echo = repeat(2) %]</span> Is there anybody out there? <span class="tt">[% END %]</span> <span class="tt">[% FILTER echo %]</span> Mother, should I build a wall? <span class="tt">[% END %]</span></pre> <p> Output: </p> <pre>Is there anybody out there? Is there anybody out there? Mother, should I build a wall? Mother, should I build a wall?</pre> <p> The <code>FILTER</code> directive automatically quotes the name of the filter. As with <code>INCLUDE</code> et al, you can use a variable to provide the name of the filter, prefixed by <code>$</code>. </p> <pre><span class="tt">[% myfilter = 'html' %]</span> <span class="tt">[% FILTER $myfilter %]</span> # same as <span class="tt">[% FILTER html %]</span> ... <span class="tt">[% END %]</span></pre> <p> A template variable can also be used to define a static filter subroutine. However, the Template Toolkit will automatically call any subroutine bound to a variable and use the value returned. Thus, the above example could be implemented as: </p> <pre>my $vars = { myfilter => sub { return 'html' }, };</pre> <p> template: </p> <pre><span class="tt">[% FILTER $myfilter %]</span> # same as <span class="tt">[% FILTER html %]</span> ... <span class="tt">[% END %]</span></pre> <p> To define a template variable that evaluates to a subroutine reference that can be used by the <code>FILTER</code> directive, you should create a subroutine that, when called automatically by the Template Toolkit, returns another subroutine reference which can then be used to perform the filter operation. Note that only static filters can be implemented in this way. </p> <pre>my $vars = { myfilter => sub { \&my_filter_sub }, }; sub my_filter_sub { my $text = shift; # do something return $text; }</pre> <p> template: </p> <pre><span class="tt">[% FILTER $myfilter %]</span> ... <span class="tt">[% END %]</span></pre> <p> Alternately, you can bless a subroutine reference into a class (any class will do) to fool the Template Toolkit into thinking it's an object rather than a subroutine. This will then bypass the automatic "call-a-subroutine-to-return-a-value" magic. </p> <pre>my $vars = { myfilter => bless(\&my_filter_sub, 'anything_you_like'), };</pre> <p> template: </p> <pre><span class="tt">[% FILTER $myfilter %]</span> ... <span class="tt">[% END %]</span></pre> <p> Filters bound to template variables remain local to the variable context in which they are defined. That is, if you define a filter in a <code>PERL</code> block within a template that is loaded via <code>INCLUDE</code>, then the filter definition will only exist until the end of that template when the stash is delocalised, restoring the previous variable state. If you want to define a filter which persists for the lifetime of the processor, or define additional dynamic filter factories, then you can call the <a href="../modules/Template/Context.html#method_define_filter">define_filter()</a> method on the current <a href="../modules/Template/Context.html">Template::Context</a> object. </p> <p> See <a href="../manual/Filters.html">Template::Manual::Filters</a> for a complete list of available filters, their descriptions and examples of use. </p> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_USE" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">USE</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>USE</code> directive can be used to load and initialise "plugin" extension modules. </p> <pre><span class="tt">[% USE myplugin %]</span></pre> <p> A plugin is a regular Perl module that conforms to a particular object-oriented interface, allowing it to be loaded into and used automatically by the Template Toolkit. For details of this interface and information on writing plugins, consult <a href="../modules/Template/Plugin.html">Template::Plugin</a>. </p> <p> A number of standard plugins are included with the Template Toolkit (see below and <a href="../manual/Plugins.html">Template::Manual::Plugins</a>). The names of these standard plugins are case insensitive. </p> <pre><span class="tt">[% USE CGI %]</span> # => Template::Plugin::CGI <span class="tt">[% USE Cgi %]</span> # => Template::Plugin::CGI <span class="tt">[% USE cgi %]</span> # => Template::Plugin::CGI</pre> <p> You can also define further plugins using the <code>PLUGINS</code> option. </p> <pre>my $tt = Template->new({ PLUGINS => { foo => 'My::Plugin::Foo', bar => 'My::Plugin::Bar', }, });</pre> <p> The recommended convention is to specify these plugin names in lower case. The Template Toolkit first looks for an exact case-sensitive match and then tries the lower case conversion of the name specified. </p> <pre><span class="tt">[% USE Foo %]</span> # look for 'Foo' then 'foo'</pre> <p> If you define all your <code>PLUGINS</code> with lower case names then they will be located regardless of how the user specifies the name in the <code>USE</code> directive. If, on the other hand, you define your <code>PLUGINS</code> with upper or mixed case names then the name specified in the <code>USE</code> directive must match the case exactly. </p> <p> If the plugin isn't defined in either the standard plugins (<code>$Template::Plugins::STD_PLUGINS</code>) or via the <code>PLUGINS</code> option, then the <code>PLUGIN_BASE</code> is searched. </p> <p> In this case the plugin name <i>is</i> case-sensitive. It is appended to each of the <code>PLUGIN_BASE</code> module namespaces in turn (default: <code>Template::Plugin</code>) to construct a full module name which it attempts to locate and load. Any periods, '<code>.</code>', in the name will be converted to '<code>::</code>'. </p> <pre><span class="tt">[% USE MyPlugin %]</span> # => Template::Plugin::MyPlugin <span class="tt">[% USE Foo.Bar %]</span> # => Template::Plugin::Foo::Bar</pre> <p> The <code>LOAD_PERL</code> option (disabled by default) provides a further way by which external Perl modules may be loaded. If a regular Perl module (i.e. not a <code>Template::Plugin::*</code> or other module relative to some <code>PLUGIN_BASE</code>) supports an object-oriented interface and a <code>new()</code> constructor then it can be loaded and instantiated automatically. The following trivial example shows how the IO::File module might be used. </p> <pre><span class="tt">[% USE file = IO.File('/tmp/mydata') %]</span> <span class="tt">[% WHILE (line = file.getline) %]</span> <!-- <span class="tt">[% line %]</span> --> <span class="tt">[% END %]</span></pre> <p> Any additional parameters supplied in parenthesis after the plugin name will be also be passed to the <code>new()</code> constructor. A reference to the current <a href="../modules/Template/Context.html">Template::Context</a> object is passed as the first parameter. </p> <pre><span class="tt">[% USE MyPlugin('foo', 123) %]</span></pre> <p> equivalent to: </p> <pre>Template::Plugin::MyPlugin->new($context, 'foo', 123);</pre> <p> The only exception to this is when a module is loaded via the <code>LOAD_PERL</code> option. In this case the <code>$context</code> reference is <i>not</i> passed to the <code>new()</code> constructor. This is based on the assumption that the module is a regular Perl module rather than a Template Toolkit plugin so isn't expecting a context reference and wouldn't know what to do with it anyway. </p> <p> Named parameters may also be specified. These are collated into a hash which is passed by reference as the last parameter to the constructor, as per the general code calling interface. </p> <pre><span class="tt">[% USE url('/cgi-bin/foo', mode='submit', debug=1) %]</span></pre> <p> equivalent to: </p> <pre>Template::Plugin::URL->new( $context, '/cgi-bin/foo' { mode => 'submit', debug => 1 } );</pre> <p> The plugin may represent any data type; a simple variable, hash, list or code reference, but in the general case it will be an object reference. Methods can be called on the object (or the relevant members of the specific data type) in the usual way: </p> <pre><span class="tt">[% USE table(mydata, rows=3) %]</span> <span class="tt">[% FOREACH row IN table.rows %]</span> <tr> <span class="tt">[% FOREACH item IN row %]</span> <td><span class="tt">[% item %]</span></td> <span class="tt">[% END %]</span> </tr> <span class="tt">[% END %]</span></pre> <p> An alternative name may be provided for the plugin by which it can be referenced: </p> <pre><span class="tt">[% USE scores = table(myscores, cols=5) %]</span> <span class="tt">[% FOREACH row IN scores.rows %]</span> ... <span class="tt">[% END %]</span></pre> <p> You can use this approach to create multiple plugin objects with different configurations. This example shows how the <a href="../modules/Template/Plugin/Format.html">format</a> plugin is used to create sub-routines bound to variables for formatting text as per <code>printf()</code>. </p> <pre><span class="tt">[% USE bold = format('<b>%s</b>') %]</span> <span class="tt">[% USE ital = format('<i>%s</i>') %]</span> <span class="tt">[% bold('This is bold') %]</span> <span class="tt">[% ital('This is italic') %]</span></pre> <p> Output: </p> <pre><b>This is bold</b> <i>This is italic</i></pre> <p> This next example shows how the <a href="../modules/Template/Plugin/URL.html">URL</a> plugin can be used to build dynamic URLs from a base part and optional query parameters. </p> <pre><span class="tt">[% USE mycgi = URL('/cgi-bin/foo.pl', debug=1) %]</span> <a href="<span class="tt">[% mycgi %]</span>">... <a href="<span class="tt">[% mycgi(mode='submit') %]</span>"...</pre> <p> Output: </p> <pre><a href="/cgi-bin/foo.pl?debug=1">... <a href="/cgi-bin/foo.pl?mode=submit&debug=1">...</pre> <p> The <a href="../modules/Template/Plugin/CGI.html">CGI</a> plugin is an example of one which delegates to another Perl module. In this this case, to Lincoln Stein's <code>CGI</code> module. All of the methods provided by the <code>CGI</code> module are available via the plugin. </p> <pre><span class="tt">[% USE CGI; CGI.start_form; CGI.checkbox_group( name = 'colours', values = [ 'red' 'green' 'blue' ] ); CGI.popup_menu( name = 'items', values = [ 'foo' 'bar' 'baz' ] ); CGI.end_form %]</span></pre> <p> See <a href="../manual/Plugins.html">Template::Manual::Plugins</a> for more information on the plugins distributed with the toolkit or available from CPAN. </p> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_MACRO" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">MACRO</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>MACRO</code> directive allows you to define a directive or directive block which is then evaluated each time the macro is called. </p> <pre><span class="tt">[% MACRO header INCLUDE header %]</span></pre> <p> Calling the macro as: </p> <pre><span class="tt">[% header %]</span></pre> <p> is then equivalent to: </p> <pre><span class="tt">[% INCLUDE header %]</span></pre> <p> Macros can be passed named parameters when called. These values remain local to the macro. </p> <pre><span class="tt">[% header(title='Hello World') %]</span></pre> <p> equivalent to: </p> <pre><span class="tt">[% INCLUDE header title='Hello World' %]</span></pre> <p> A <code>MACRO</code> definition may include parameter names. Values passed to the macros are then mapped to these local variables. Other named parameters may follow these. </p> <pre><span class="tt">[% MACRO header(title) INCLUDE header %]</span> <span class="tt">[% header('Hello World') %]</span> <span class="tt">[% header('Hello World', bgcol='#123456') %]</span></pre> <p> equivalent to: </p> <pre><span class="tt">[% INCLUDE header title='Hello World' %]</span> <span class="tt">[% INCLUDE header title='Hello World' bgcol='#123456' %]</span></pre> <p> Here's another example, defining a macro for display numbers in comma-delimited groups of 3, using the chunk and join virtual method. </p> <pre><span class="tt">[% MACRO number(n) GET n.chunk(-3).join(',') %]</span> <span class="tt">[% number(1234567) %]</span> # 1,234,567</pre> <p> A <code>MACRO</code> may precede any directive and must conform to the structure of the directive. </p> <pre><span class="tt">[% MACRO header IF frames %]</span> <span class="tt">[% INCLUDE frames/header %]</span> <span class="tt">[% ELSE %]</span> <span class="tt">[% INCLUDE header %]</span> <span class="tt">[% END %]</span> <span class="tt">[% header %]</span></pre> <p> A <code>MACRO</code> may also be defined as an anonymous <code>BLOCK</code>. The block will be evaluated each time the macro is called. </p> <pre><span class="tt">[% MACRO header BLOCK %]</span> ...content... <span class="tt">[% END %]</span> <span class="tt">[% header %]</span></pre> <p> If you've got the <code>EVAL_PERL</code> option set, then you can even define a <code>MACRO</code> as a <code>PERL</code> block (see below): </p> <pre><span class="tt">[% MACRO triple(n) PERL %]</span> my $n = $stash->get('n'); print $n * 3; <span class="tt">[% END -%]</span></pre> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_PERL" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">PERL</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> (for the advanced reader) </p> <p> The <code>PERL</code> directive is used to mark the start of a block which contains Perl code for evaluation. The <code>EVAL_PERL</code> option must be enabled for Perl code to be evaluated or a <code>perl</code> exception will be thrown with the message '<code>EVAL_PERL not set</code>'. </p> <p> Perl code is evaluated in the <code>Template::Perl</code> package. The <code>$context</code> package variable contains a reference to the current <a href="../modules/Template/Context.html">Template::Context</a> object. This can be used to access the functionality of the Template Toolkit to process other templates, load plugins, filters, etc. See <a href="../modules/Template/Context.html">Template::Context</a> for further details. </p> <pre><span class="tt">[% PERL %]</span> print $context->include('myfile'); <span class="tt">[% END %]</span></pre> <p> The <a href="#section_$stash">$stash</a> variable contains a reference to the top-level stash object which manages template variables. Through this, variable values can be retrieved and updated. See <a href="../modules/Template/Stash.html">Template::Stash</a> for further details. </p> <pre><span class="tt">[% PERL %]</span> $stash->set(foo => 'bar'); print "foo value: ", $stash->get('foo'); <span class="tt">[% END %]</span></pre> <p> Output: </p> <pre>foo value: bar</pre> <p> Output is generated from the <code>PERL</code> block by calling <code>print()</code>. Note that the <code>Template::Perl::PERLOUT</code> handle is selected (tied to an output buffer) instead of <code>STDOUT</code>. </p> <pre><span class="tt">[% PERL %]</span> print "foo\n"; # OK print PERLOUT "bar\n"; # OK, same as above print Template::Perl::PERLOUT "baz\n"; # OK, same as above print STDOUT "qux\n"; # WRONG! <span class="tt">[% END %]</span></pre> <p> The <code>PERL</code> block may contain other template directives. These are processed before the Perl code is evaluated. </p> <pre><span class="tt">[% name = 'Fred Smith' %]</span> <span class="tt">[% PERL %]</span> print "<span class="tt">[% name %]</span>\n"; <span class="tt">[% END %]</span></pre> <p> Thus, the Perl code in the above example is evaluated as: </p> <pre>print "Fred Smith\n";</pre> <p> Exceptions may be thrown from within <code>PERL</code> blocks using <code>die()</code>. They will be correctly caught by enclosing <code>TRY</code> blocks. </p> <pre><span class="tt">[% TRY %]</span> <span class="tt">[% PERL %]</span> die "nothing to live for\n"; <span class="tt">[% END %]</span> <span class="tt">[% CATCH %]</span> error: <span class="tt">[% error.info %]</span> <span class="tt">[% END %]</span></pre> <p> output: error: nothing to live for </p> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_RAWPERL" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">RAWPERL</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> (for the very advanced reader) </p> <p> The Template Toolkit parser reads a source template and generates the text of a Perl subroutine as output. It then uses <code>eval()</code> to evaluate it into a subroutine reference. This subroutine is then called to process the template, passing a reference to the current <a href="../modules/Template/Context.html">Template::Context</a> object through which the functionality of the Template Toolkit can be accessed. The subroutine reference can be cached, allowing the template to be processed repeatedly without requiring any further parsing. </p> <p> For example, a template such as: </p> <pre><span class="tt">[% PROCESS header %]</span> The <span class="tt">[% animal %]</span> sat on the <span class="tt">[% location %]</span> <span class="tt">[% PROCESS footer %]</span></pre> <p> is converted into the following Perl subroutine definition: </p> <pre>sub { my $context = shift; my $stash = $context->stash; my $output = ''; my $error; eval { BLOCK: { $output .= $context->process('header'); $output .= "The "; $output .= $stash->get('animal'); $output .= " sat on the "; $output .= $stash->get('location'); $output .= $context->process('footer'); $output .= "\n"; } }; if ($@) { $error = $context->catch($@, \$output); die $error unless $error->type eq 'return'; } return $output; }</pre> <p> To examine the Perl code generated, such as in the above example, set the <code>$Template::Parser::DEBUG</code> package variable to any true value. You can also set the <code>$Template::Directive::PRETTY</code> variable true to have the code formatted in a readable manner for human consumption. The source code for each generated template subroutine will be printed to <code>STDERR</code> on compilation (i.e. the first time a template is used). </p> <pre>$Template::Parser::DEBUG = 1; $Template::Directive::PRETTY = 1; $template->process($file, $vars) || die $template->error(), "\n";</pre> <p> The <code>PERL</code> ... <code>END</code> construct allows Perl code to be embedded into a template when the <code>EVAL_PERL</code> option is set. It is evaluated at "runtime" using <code>eval()</code> each time the template subroutine is called. This is inherently flexible, but not as efficient as it could be, especially in a persistent server environment where a template may be processed many times. </p> <p> The <code>RAWPERL</code> directive allows you to write Perl code that is integrated directly into the generated Perl subroutine text. It is evaluated once at compile time and is stored in cached form as part of the compiled template subroutine. This makes <code>RAWPERL</code> blocks more efficient than <code>PERL</code> blocks. </p> <p> The downside is that you must code much closer to the metal. For example, in a <code>PERL</code> block you can call <a href="#method_print">print()</a> to generate some output. <code>RAWPERL</code> blocks don't afford such luxury. The code is inserted directly into the generated subroutine text and should conform to the convention of appending to the <code>$output</code> variable. </p> <pre><span class="tt">[% PROCESS header %]</span> <span class="tt">[% RAWPERL %]</span> $output .= "Some output\n"; ... $output .= "Some more output\n"; <span class="tt">[% END %]</span></pre> <p> The critical section of the generated subroutine for this example would then look something like: </p> <pre>... eval { BLOCK: { $output .= $context->process('header'); $output .= "\n"; $output .= "Some output\n"; ... $output .= "Some more output\n"; $output .= "\n"; } }; ...</pre> <p> As with <code>PERL</code> blocks, the <a href="../modules/Template/Context.html">$context</a> and <a href="../modules/Template/Stash.html">$stash</a> references are pre-defined and available for use within <code>RAWPERL</code> code. </p> </div> </div> </div> </div> <div class="section"> <div class="head"> <h1 id="Exception_Handling_and_Flow_Control" onclick="switch_section(this)" title="Click title to show/hide section content.">Exception Handling and Flow Control</h1> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <div class="subsection"> <div class="head"> <h2 id="section_TRY_THROW_CATCH_FINAL" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">TRY / THROW / CATCH / FINAL</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> (more advanced material) </p> <p> The Template Toolkit supports fully functional, nested exception handling. The <code>TRY</code> directive introduces an exception handling scope which continues until the matching <code>END</code> directive. Any errors that occur within that block will be caught and can be handled by one of the <code>CATCH</code> blocks defined. </p> <pre><span class="tt">[% TRY %]</span> ...blah...blah... <span class="tt">[% CALL somecode %]</span> ...etc... <span class="tt">[% INCLUDE someblock %]</span> ...and so on... <span class="tt">[% CATCH %]</span> An error occurred! <span class="tt">[% END %]</span></pre> <p> Errors are raised as exceptions (objects of the <a href="../modules/Template/Exception.html">Template::Exception</a> class) which contain two fields: <code>type</code> and <code>info</code>. The exception <code>type</code> is used to indicate the kind of error that occurred. It is a simple text string which can contain letters, numbers, '<code>_</code>' or '<code>.</code>'. The <code>info</code> field contains an error message indicating what actually went wrong. Within a catch block, the exception object is aliased to the <code>error</code> variable. You can access the <code>type</code> and <code>info</code> fields directly. </p> <pre><span class="tt">[% mydsn = 'dbi:MySQL:foobar' %]</span> ... <span class="tt">[% TRY %]</span> <span class="tt">[% USE DBI(mydsn) %]</span> <span class="tt">[% CATCH %]</span> ERROR! Type: <span class="tt">[% error.type %]</span> Info: <span class="tt">[% error.info %]</span> <span class="tt">[% END %]</span></pre> <p> output (assuming a non-existant database called '<code>foobar</code>'): </p> <pre>ERROR! Type: DBI Info: Unknown database "foobar"</pre> <p> The <code>error</code> variable can also be specified by itself and will return a string of the form "<code>$type error - $info</code>". </p> <pre>... <span class="tt">[% CATCH %]</span> ERROR: <span class="tt">[% error %]</span> <span class="tt">[% END %]</span></pre> <p> Output: </p> <pre>ERROR: DBI error - Unknown database "foobar"</pre> <p> Each <code>CATCH</code> block may be specified with a particular exception type denoting the kind of error that it should catch. Multiple <code>CATCH</code> blocks can be provided to handle different types of exception that may be thrown in the <code>TRY</code> block. A <code>CATCH</code> block specified without any type, as in the previous example, is a default handler which will catch any otherwise uncaught exceptions. This can also be specified as <code>[% CATCH DEFAULT %]</code>. </p> <pre><span class="tt">[% TRY %]</span> <span class="tt">[% INCLUDE myfile %]</span> <span class="tt">[% USE DBI(mydsn) %]</span> <span class="tt">[% CALL somecode %]</span> <span class="tt">[% CATCH file %]</span> File Error! <span class="tt">[% error.info %]</span> <span class="tt">[% CATCH DBI %]</span> <span class="tt">[% INCLUDE database/error.html %]</span> <span class="tt">[% CATCH %]</span> <span class="tt">[% error %]</span> <span class="tt">[% END %]</span></pre> <p> Remember that you can specify multiple directives within a single tag, each delimited by '<code>;</code>'. So the above example can be written more concisely as: </p> <pre><span class="tt">[% TRY; INCLUDE myfile; USE DBI(mydsn); CALL somecode; CATCH file; "File Error! $error.info"; CATCH DBI; INCLUDE database/error.html; CATCH; error; END %]</span></pre> <p> The <code>DBI</code> plugin throws exceptions of the <code>DBI</code> type (in case that wasn't already obvious). The other specific exception caught here is of the <code>file</code> type. </p> <p> A <code>file</code> exception is automatically thrown by the Template Toolkit when it can't find a file, or fails to load, parse or process a file that has been requested by an <code>INCLUDE</code>, <code>PROCESS</code>, <code>INSERT</code> or <code>WRAPPER</code> directive. If <code>myfile</code> can't be found in the example above, the <code>[% INCLUDE myfile %]</code> directive will raise a <code>file</code> exception which is then caught by the <code>[% CATCH file %]</code> block. The output generated would be: </p> <pre>File Error! myfile: not found</pre> <p> Note that the <code>DEFAULT</code> option (disabled by default) allows you to specify a default file to be used any time a template file can't be found. This will prevent file exceptions from ever being raised when a non-existant file is requested (unless, of course, the <code>DEFAULT</code> file your specify doesn't exist). Errors encountered once the file has been found (i.e. read error, parse error) will be raised as file exceptions as per usual. </p> <p> Uncaught exceptions (i.e. if the <code>TRY</code> block doesn't have a type specific or default <code>CATCH</code> handler) may be caught by enclosing <code>TRY</code> blocks which can be nested indefinitely across multiple templates. If the error isn't caught at any level then processing will stop and the Template <a href="../modules/Template.html#method_process">process()</a> method will return a false value to the caller. The relevant <a href="../modules/Template/Exception.html">Template::Exception</a> object can be retrieved by calling the <a href="../modules/Template.html#method_error">error()</a> method. </p> <pre><span class="tt">[% TRY %]</span> ... <span class="tt">[% TRY %]</span> <span class="tt">[% INCLUDE $user.header %]</span> <span class="tt">[% CATCH file %]</span> <span class="tt">[% INCLUDE header %]</span> <span class="tt">[% END %]</span> ... <span class="tt">[% CATCH DBI %]</span> <span class="tt">[% INCLUDE database/error.html %]</span> <span class="tt">[% END %]</span></pre> <p> In this example, the inner <code>TRY</code> block is used to ensure that the first <code>INCLUDE</code> directive works as expected. We're using a variable to provide the name of the template we want to include, <code>user.header</code>, and it's possible this contains the name of a non-existant template, or perhaps one containing invalid template directives. If the <code>INCLUDE</code> fails with a <code>file</code> error then we <code>CATCH</code> it in the inner block and <code>INCLUDE</code> the default <code>header</code> file instead. Any <code>DBI</code> errors that occur within the scope of the outer <code>TRY</code> block will be caught in the relevant <code>CATCH</code> block, causing the <code>database/error.html</code> template to be processed. Note that included templates inherit all currently defined template variable so these error files can quite happily access the <error> variable to retrieve information about the currently caught exception. For example, the <code>database/error.html</code> template might look like this: </p> <pre><h2>Database Error</h2> A database error has occurred: <span class="tt">[% error.info %]</span></pre> <p> You can also specify a <code>FINAL</code> block. This is always processed regardless of the outcome of the <code>TRY</code> and/or <code>CATCH</code> blocks. If an exception is uncaught then the <code>FINAL</code> block is processed before jumping to the enclosing block or returning to the caller. </p> <pre><span class="tt">[% TRY %]</span> ... <span class="tt">[% CATCH this %]</span> ... <span class="tt">[% CATCH that %]</span> ... <span class="tt">[% FINAL %]</span> All done! <span class="tt">[% END %]</span></pre> <p> The output from the <code>TRY</code> block is left intact up to the point where an exception occurs. For example, this template: </p> <pre><span class="tt">[% TRY %]</span> This gets printed <span class="tt">[% THROW food 'carrots' %]</span> This doesn't <span class="tt">[% CATCH food %]</span> culinary delights: <span class="tt">[% error.info %]</span> <span class="tt">[% END %]</span></pre> <p> generates the following output: </p> <pre>This gets printed culinary delights: carrots</pre> <p> The <code>CLEAR</code> directive can be used in a <code>CATCH</code> or <code>FINAL</code> block to clear any output created in the <code>TRY</code> block. </p> <pre><span class="tt">[% TRY %]</span> This gets printed <span class="tt">[% THROW food 'carrots' %]</span> This doesn't <span class="tt">[% CATCH food %]</span> <span class="tt">[% CLEAR %]</span> culinary delights: <span class="tt">[% error.info %]</span> <span class="tt">[% END %]</span></pre> <p> Output: </p> <pre>culinary delights: carrots</pre> <p> Exception types are hierarchical, with each level being separated by the familiar dot operator. A <code>DBI.connect</code> exception is a more specific kind of <code>DBI</code> error. Similarly, an <code>example.error.barf</code> is a more specific kind of <code>example.error</code> type which itself is also a <code>example</code> error. </p> <p> A <code>CATCH</code> handler that specifies a general exception type (such as <code>DBI</code> or <code>example.error</code>) will also catch more specific types that have the same prefix as long as a more specific handler isn't defined. Note that the order in which <code>CATCH</code> handlers are defined is irrelevant; a more specific handler will always catch an exception in preference to a more generic or default one. </p> <pre><span class="tt">[% TRY %]</span> ... <span class="tt">[% CATCH DBI ; INCLUDE database/error.html ; CATCH DBI.connect ; INCLUDE database/connect.html ; CATCH ; INCLUDE error.html ; END %]</span></pre> <p> In this example, a <code>DBI.connect</code> error has it's own handler, a more general <code>DBI</code> block is used for all other <code>DBI</code> or <code>DBI.*</code> errors and a default handler catches everything else. </p> <p> Exceptions can be raised in a template using the <code>THROW</code> directive. The first parameter is the exception type which doesn't need to be quoted (but can be, it's the same as <code>INCLUDE</code>) followed by the relevant error message which can be any regular value such as a quoted string, variable, etc. </p> <pre><span class="tt">[% THROW food "Missing ingredients: $recipe.error" %]</span> <span class="tt">[% THROW user.login 'no user id: please login' %]</span> <span class="tt">[% THROW $myerror.type "My Error: $myerror.info" %]</span></pre> <p> It's also possible to specify additional positional or named parameters to the <code>THROW</code> directive if you want to pass more than just a simple message back as the error info field. </p> <pre><span class="tt">[% THROW food 'eggs' 'flour' msg='Missing Ingredients' %]</span></pre> <p> In this case, the error <code>info</code> field will be a hash array containing the named arguments and an <code>args</code> item which contains a list of the positional arguments. </p> <pre>type => 'food', info => { msg => 'Missing Ingredients', args => ['eggs', 'flour'], }</pre> <p> In addition to specifying individual positional arguments as <code>[% error.info.args.n %]</code>, the <code>info</code> hash contains keys directly pointing to the positional arguments, as a convenient shortcut. </p> <pre><span class="tt">[% error.info.0 %]</span> # same as <span class="tt">[% error.info.args.0 %]</span></pre> <p> Exceptions can also be thrown from Perl code which you've bound to template variables, or defined as a plugin or other extension. To raise an exception, call <code>die()</code> passing a reference to a <a href="../modules/Template/Exception.html">Template::Exception</a> object as the argument. This will then be caught by any enclosing <code>TRY</code> blocks from where the code was called. </p> <pre>use Template::Exception; ... my $vars = { foo => sub { # ... do something ... die Template::Exception->new('myerr.naughty', 'Bad, bad error'); }, };</pre> <p> Template: </p> <pre><span class="tt">[% TRY %]</span> <span class="tt">[% foo %]</span> <span class="tt">[% CATCH myerr ; "Error: $error" ; END %]</span></pre> <p> Output: </p> <pre>Error: myerr.naughty error - Bad, bad error</pre> <p> The <code>info</code> field can also be a reference to another object or data structure, if required. </p> <pre>die Template::Exception->new('myerror', { module => 'foo.pl', errors => [ 'bad permissions', 'naughty boy' ], });</pre> <p> Later, in a template: </p> <pre><span class="tt">[% TRY %]</span> ... <span class="tt">[% CATCH myerror %]</span> <span class="tt">[% error.info.errors.size or 'no'; error.info.errors.size == 1 ? ' error' : ' errors' %]</span> in <span class="tt">[% error.info.module %]</span>: <span class="tt">[% error.info.errors.join(', ') %]</span>. <span class="tt">[% END %]</span></pre> <p> Generating the output: </p> <pre>2 errors in foo.pl: bad permissions, naughty boy.</pre> <p> You can also call <code>die()</code> with a single string, as is common in much existing Perl code. This will automatically be converted to an exception of the '<code>undef</code>' type (that's the literal string '<code>undef</code>', not the undefined value). If the string isn't terminated with a newline then Perl will append the familiar <code>" at $file line $line"</code> message. </p> <pre>sub foo { # ... do something ... die "I'm sorry, Dave, I can't do that\n"; }</pre> <p> If you're writing a plugin, or some extension code that has the current <a href="../modules/Template/Context.html">Template::Context</a> in scope (you can safely skip this section if this means nothing to you) then you can also raise an exception by calling the context <a href="../modules/Template/Context.html#method_throw">throw()</a> method. You can pass it an <a href="../modules/Template/Exception.html">Template::Exception</a> object reference, a pair of <code>($type, $info)</code> parameters or just an <code>$info</code> string to create an exception of '<code>undef</code>' type. </p> <pre>$context->throw($e); # exception object $context->throw('Denied'); # 'undef' type $context->throw('user.passwd', 'Bad Password');</pre> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_NEXT" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">NEXT</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>NEXT</code> directive can be used to start the next iteration of a <code>FOREACH</code> or <code>WHILE</code> loop. </p> <pre><span class="tt">[% FOREACH user IN users %]</span> <span class="tt">[% NEXT IF user.isguest %]</span> Name: <span class="tt">[% user.name %]</span> Email: <span class="tt">[% user.email %]</span> <span class="tt">[% END %]</span></pre> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_LAST" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">LAST</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>LAST</code> directive can be used to prematurely exit a <code>FOREACH</code> or <code>WHILE</code> loop. </p> <pre><span class="tt">[% FOREACH user IN users %]</span> Name: <span class="tt">[% user.name %]</span> Email: <span class="tt">[% user.email %]</span> <span class="tt">[% LAST IF some.condition %]</span> <span class="tt">[% END %]</span></pre> <p> <code>BREAK</code> can also be used as an alias for <code>LAST</code>. </p> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_RETURN" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">RETURN</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>RETURN</code> directive can be used to stop processing the current template and return to the template from which it was called, resuming processing at the point immediately after the <code>INCLUDE</code>, <code>PROCESS</code> or <code>WRAPPER</code> directive. If there is no enclosing template then the Template <a href="../modules/Template.html#method_process">process()</a> method will return to the calling code with a true value. </p> <pre>Before <span class="tt">[% INCLUDE half_wit %]</span> After <span class="tt">[% BLOCK half_wit %]</span> This is just half... <span class="tt">[% RETURN %]</span> ...a complete block <span class="tt">[% END %]</span></pre> <p> Output: </p> <pre>Before This is just half... After</pre> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_STOP" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">STOP</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>STOP</code> directive can be used to indicate that the processor should stop gracefully without processing any more of the template document. This is a planned stop and the Template <a href="../modules/Template.html#method_process">process()</a> method will return a <b>true</b> value to the caller. This indicates that the template was processed successfully according to the directives within it. </p> <pre><span class="tt">[% IF something.terrible.happened %]</span> <span class="tt">[% INCLUDE fatal/error.html %]</span> <span class="tt">[% STOP %]</span> <span class="tt">[% END %]</span> <span class="tt">[% TRY %]</span> <span class="tt">[% USE DBI(mydsn) %]</span> ... <span class="tt">[% CATCH DBI.connect %]</span> <h1>Cannot connect to the database: <span class="tt">[% error.info %]</span></h1> <p> We apologise for the inconvenience. </p> <span class="tt">[% INCLUDE footer %]</span> <span class="tt">[% STOP %]</span> <span class="tt">[% END %]</span></pre> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_CLEAR" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">CLEAR</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>CLEAR</code> directive can be used to clear the output buffer for the current enclosing block. It is most commonly used to clear the output generated from a <code>TRY</code> block up to the point where the error occurred. </p> <pre><span class="tt">[% TRY %]</span> blah blah blah # this is normally left intact <span class="tt">[% THROW some 'error' %]</span> # up to the point of error ... <span class="tt">[% CATCH %]</span> <span class="tt">[% CLEAR %]</span> # clear the TRY output <span class="tt">[% error %]</span> # print error string <span class="tt">[% END %]</span></pre> </div> </div> </div> </div> <div class="section"> <div class="head"> <h1 id="Miscellaneous" onclick="switch_section(this)" title="Click title to show/hide section content.">Miscellaneous</h1> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <div class="subsection"> <div class="head"> <h2 id="section_META" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">META</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>META</code> directive allows simple metadata items to be defined within a template. These are evaluated when the template is parsed and as such may only contain simple values (e.g. it's not possible to interpolate other variables values into <code>META</code> variables). </p> <pre><span class="tt">[% META title = 'The Cat in the Hat' author = 'Dr. Seuss' version = 1.23 %]</span></pre> <p> The <code>template</code> variable contains a reference to the main template being processed. These metadata items may be retrieved as attributes of the template. </p> <pre><h1><span class="tt">[% template.title %]</span></h1> <h2><span class="tt">[% template.author %]</span></h2></pre> <p> The <code>name</code> and <code>modtime</code> metadata items are automatically defined for each template to contain its name and modification time in seconds since the epoch. </p> <pre><span class="tt">[% USE date %]</span> # use Date plugin to format time ... <span class="tt">[% template.name %]</span> last modified at <span class="tt">[% date.format(template.modtime) %]</span></pre> <p> The <code>PRE_PROCESS</code> and <code>POST_PROCESS</code> options allow common headers and footers to be added to all templates. The <code>template</code> reference is correctly defined when these templates are processed, allowing headers and footers to reference metadata items from the main template. </p> <pre>$template = Template->new({ PRE_PROCESS => 'header', POST_PROCESS => 'footer', }); $template->process('cat_in_hat');</pre> <p> header: </p> <pre><html> <head> <title><span class="tt">[% template.title %]</span></title> </head> <body></pre> <p> cat_in_hat: </p> <pre><span class="tt">[% META title = 'The Cat in the Hat' author = 'Dr. Seuss' version = 1.23 year = 2000 %]</span> The cat in the hat sat on the mat.</pre> <p> footer: </p> <pre> <hr> &copy; <span class="tt">[% template.year %]</span> <span class="tt">[% template.author %]</span> </body> </html></pre> <p> The output generated from the above example is: </p> <pre><html> <head> <title>The Cat in the Hat</title> </head> <body> The cat in the hat sat on the mat. <hr> &copy; 2000 Dr. Seuss </body> </html></pre> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_TAGS" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">TAGS</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>TAGS</code> directive can be used to set the <code>START_TAG</code> and <code>END_TAG</code> values on a per-template file basis. </p> <pre><span class="tt">[% TAGS <+ +> %]</span> <+ INCLUDE header +></pre> <p> The TAGS directive may also be used to set a named <code>TAG_STYLE</code> </p> <pre><span class="tt">[% TAGS html %]</span> <!-- INCLUDE header --></pre> <p> See the <a href="../manual/Config.html#section_TAGS">TAGS</a> and <a href="../manual/Config.html#section_TAG_STYLE">TAG_STYLE</a> configuration options for further details. </p> </div> </div> <div class="subsection"> <div class="head"> <h2 id="section_DEBUG" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">DEBUG</h2> <a href="#body" class="top" title="Back up to the top of the page" >Top</a> </div> <div class="body"> <p> The <code>DEBUG</code> directive can be used to enable or disable directive debug messages within a template. The <code>DEBUG</code> configuration option must be set to include <code>DEBUG_DIRS</code> for the <code>DEBUG</code> directives to have any effect. If <code>DEBUG_DIRS</code> is not set then the parser will automatically ignore and remove any <code>DEBUG</code> directives. </p> <p> The <code>DEBUG</code> directive can be used with an <code>on</code> or <code>off</code> parameter to enable or disable directive debugging messages from that point forward. When enabled, the output of each directive in the generated output will be prefixed by a comment indicate the file, line and original directive text. </p> <pre><span class="tt">[% DEBUG on %]</span> directive debugging is on (assuming DEBUG option is set true) <span class="tt">[% DEBUG off %]</span> directive debugging is off</pre> <p> The <code>format</code> parameter can be used to change the format of the debugging message. </p> <pre><span class="tt">[% DEBUG format '<!-- $file line $line : [% $text %]</span> -->' %]</pre> </div> </div> </div> </div> </div></div> <br class="clear" /> <div class="pageinfo"> <a href="http://template-toolkit.org/docs/manual/Directives.html">http://template-toolkit.org/docs/manual/Directives.html</a> </div> </div> <div id="footer"> <a href="http://opensource.org/" class="osi"></a> <div class="controls"> <div class="pager"> <a href="../manual/Syntax.html" title="Template::Manual::Syntax" class="go back">Back<span class="about"><h4>Template::Manual::Syntax</h4></span></a> <a href="../manual/index.html" title="Template::Manual" class="go up">Up<span class="about"><h4>Template::Manual</h4></span></a> <a href="../manual/Variables.html" title="Template::Manual::Variables" class="go next">Next<span class="about"><h4>Template::Manual::Variables</h4></span></a> </div> </div> <div class="copyright"> Copyright © 1996-2012 <a href="http://wardley.org/">Andy Wardley</a>. All Rights Reserved. </div> <div class="licence"> The <a href="http://template-toolkit.org/">Template Toolkit</a> is <a href="http://opensource.org/">Open Source</a> software. You can redistribute and/or modify it under the terms of the <a href="http://www.opensource.org/licenses/gpl-license.php">GNU Public Licence</a> or the <a href="http://www.opensource.org/licenses/artistic-license.php">Perl Artistic Licence</a>. </div> </div> <div id="palette"> <ul> <li class="first"><a href="#" class="blue" onclick="set_style('Clear Blue')"></a></li> <li><a href="#" class="orange" onclick="set_style('Clear Orange')"></a></li> <li><a href="#" class="green" onclick="set_style('Clear Green')"></a></li> <li><a href="#" class="purple" onclick="set_style('Clear Purple')"></a></li> <li><a href="#" class="grey" onclick="set_style('Clear Grey')"></a></li> </ul> </div> </div> </body> </html>