{
    "content": [
        {
            "type": "text",
            "text": "# Template::Manual::Directives (perldoc)\n\n## NAME\n\nTemplate::Manual::Directives - Template directives\n\n## Sections\n\n- **NAME**\n- **Accessing and Updating Template Variables**\n- **Processing Template Files and Blocks** (1 subsections)\n- **Conditional Processing**\n- **Loop Processing**\n- **Filters, Plugins, Macros and Perl** (1 subsections)\n- **Exception Handling and Flow Control** (1 subsections)\n- **Miscellaneous**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "Template::Manual::Directives",
        "section": "",
        "mode": "perldoc",
        "summary": "Template::Manual::Directives - Template directives",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "Accessing and Updating Template Variables",
                "lines": 117,
                "subsections": []
            },
            {
                "name": "Processing Template Files and Blocks",
                "lines": 314,
                "subsections": [
                    {
                        "name": "<i>Hello World</i>",
                        "lines": 47
                    }
                ]
            },
            {
                "name": "Conditional Processing",
                "lines": 62,
                "subsections": []
            },
            {
                "name": "Loop Processing",
                "lines": 200,
                "subsections": []
            },
            {
                "name": "Filters, Plugins, Macros and Perl",
                "lines": 281,
                "subsections": [
                    {
                        "name": "This is bold",
                        "lines": 255
                    }
                ]
            },
            {
                "name": "Exception Handling and Flow Control",
                "lines": 327,
                "subsections": [
                    {
                        "name": "process",
                        "lines": 53
                    }
                ]
            },
            {
                "name": "Miscellaneous",
                "lines": 110,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "Template::Manual::Directives - Template directives\n",
                "subsections": []
            },
            "Accessing and Updating Template Variables": {
                "content": "GET\nThe \"GET\" directive retrieves and outputs the value of the named variable.\n\n[% GET foo %]\n\nThe \"GET\" keyword is optional. A variable can be specified in a directive tag by itself.\n\n[% foo %]\n\nThe variable can have an unlimited number of elements, each separated by a dot. Each element can\nhave arguments specified within parentheses.\n\n[% foo %]\n[% bar.baz %]\n[% biz.baz(10) %]\n...etc...\n\nSee Template::Manual::Variables for a full discussion on template variables.\n\nYou can also specify expressions using the logical (\"and\", \"or\", \"not\", \"?\", \":\") and mathematic\noperators (\"+\", \"-\", \"*\", \"/\", \"%\", \"mod\", \"div\").\n\n[% template.title or default.title %]\n\n[% score * 100 %]\n\n[% order.nitems ? checkout(order.total) : 'no items' %]\n\nThe \"div\" operator returns the integer result of division. Both \"%\" and \"mod\" return the modulus\n(i.e. remainder) of division.\n\n[% 15 / 6 %]            # 2.5\n[% 15 div 6 %]          # 2\n[% 15 mod 6 %]          # 3\n\nCALL\nThe \"CALL\" directive is similar to \"GET\" in evaluating the variable named, but doesn't print the\nresult returned. This can be useful when a variable is bound to a sub-routine or object method\nwhich you want to call but aren't interested in the value returned.\n\n[% CALL dbi.disconnect %]\n\n[% CALL incpagecounter(pagecount) %]\n\nSET\nThe \"SET\" directive allows you to assign new values to existing variables or create new\ntemporary variables.\n\n[% SET title = 'Hello World' %]\n\nThe \"SET\" keyword is also optional.\n\n[% title = 'Hello World' %]\n\nVariables may be assigned the values of other variables, unquoted numbers (2.718), literal text\n('single quotes') or quoted text (\"double quotes\"). In the latter case, any variable references\nwithin the text will be interpolated when the string is evaluated. Variables should be prefixed\nby \"$\", using curly braces to explicitly scope the variable name where necessary.\n\n[% foo  = 'Foo'  %]               # literal value 'Foo'\n[% bar  =  foo   %]               # value of variable 'foo'\n[% cost = '$100' %]               # literal value '$100'\n[% item = \"$bar: ${cost}.00\" %]   # value \"Foo: $100.00\"\n\nMultiple variables may be assigned in the same directive and are evaluated in the order\nspecified. Thus, the above could have been written:\n\n[% foo  = 'Foo'\nbar  = foo\ncost = '$100'\nitem = \"$bar: ${cost}.00\"\n%]\n\nSimple expressions can also be used, as per \"GET\".\n\n[% ten    = 10\ntwenty = 20\nthirty = twenty + ten\nforty  = 2 * twenty\nfifty  = 100 div 2\nsix    = twenty mod 7\n%]\n\nYou can concatenate strings together using the '  ' operator. In Perl 5, the \".\" is used for\nstring concatenation, but in Perl 6, as in the Template Toolkit, the \".\" will be used as the\nmethod calling operator and '  ' will be used for string concatenation. Note that the operator\nmust be specified with surrounding whitespace which, as Larry says, is construed as a feature:\n\n[% copyright = '(C) Copyright'  year  ' '  author %]\n\nYou can, of course, achieve a similar effect with double quoted string interpolation.\n\n[% copyright = \"(C) Copyright $year $author\" %]\n\nDEFAULT\nThe \"DEFAULT\" directive is similar to \"SET\" but only updates variables that are currently\nundefined or have no \"true\" value (in the Perl sense).\n\n[% DEFAULT\nname = 'John Doe'\nid   = 'jdoe'\n%]\n\nThis can be particularly useful in common template components to ensure that some sensible\ndefault are provided for otherwise undefined variables.\n\n[% DEFAULT\ntitle = 'Hello World'\nbgcol = '#ffffff'\n%]\n<html>\n<head>\n<title>[% title %]</title>\n</head>\n<body bgcolor=\"[% bgcol %]\">\n...etc...\n",
                "subsections": []
            },
            "Processing Template Files and Blocks": {
                "content": "INSERT\nThe \"INSERT\" directive is used to insert the contents of an external file at the current\nposition.\n\n[% INSERT myfile %]\n\nNo attempt to parse or process the file is made. The contents, possibly including any embedded\ntemplate directives, are inserted intact.\n\nThe filename specified should be relative to one of the \"INCLUDEPATH\" directories. Absolute\n(i.e. starting with \"/\") and relative (i.e. starting with \".\") filenames may be used if the\n\"ABSOLUTE\" and \"RELATIVE\" options are set, respectively. Both these options are disabled by\ndefault.\n\nmy $template = Template->new({\nINCLUDEPATH => '/here:/there',\n});\n\n$template->process('myfile');\n\nmyfile:\n\n[% INSERT foo %]            # looks for /here/foo then /there/foo\n[% INSERT /etc/passwd %]    # file error: ABSOLUTE not set\n[% INSERT ../secret %]      # file error: RELATIVE not set\n\nFor convenience, the filename does not need to be quoted as long as it contains only\nalphanumeric characters, underscores, dots or forward slashes. Names containing any other\ncharacters should be quoted.\n\n[% INSERT misc/legalese.txt            %]\n[% INSERT 'dos98/Program Files/stupid' %]\n\nTo evaluate a variable to specify a filename, you should explicitly prefix it with a \"$\" or use\ndouble-quoted string interpolation.\n\n[% language = 'en'\nlegalese = 'misc/legalese.txt'\n%]\n\n[% INSERT $legalese %]              # misc/legalese.txt\n[% INSERT \"$language/$legalese\" %]  # en/misc/legalese.txt\n\nMultiple files can be specified using \"+\" as a delimiter. All files should be unquoted names or\nquoted strings. Any variables should be interpolated into double-quoted strings.\n\n[% INSERT legalese.txt + warning.txt %]\n[% INSERT  \"$legalese\" + warning.txt %]  # requires quoting\n\nINCLUDE\nThe \"INCLUDE\" directive is used to process and include the output of another template file or\nblock.\n\n[% INCLUDE header %]\n\nIf a \"BLOCK\" of the specified name is defined in the same file, or in a file from which the\ncurrent template has been called (i.e. a parent template) then it will be used in preference to\nany file of the same name.\n\n[% INCLUDE table %]     # uses BLOCK defined below\n\n[% BLOCK table %]\n<table>\n...\n</table>\n[% END %]\n\nIf a \"BLOCK\" definition is not currently visible then the template name should be a file\nrelative to one of the \"INCLUDEPATH\" directories, or an absolute or relative file name if the\n\"ABSOLUTE\"/\"RELATIVE\" options are appropriately enabled. The \"INCLUDE\" directive automatically\nquotes the filename specified, as per \"INSERT\" described above. When a variable contains the\nname of the template for the \"INCLUDE\" directive, it should be explicitly prefixed by \"$\" or\ndouble-quoted\n\n[% myheader = 'my/misc/header' %]\n[% INCLUDE   myheader  %]           # 'myheader'\n[% INCLUDE  $myheader  %]           # 'my/misc/header'\n[% INCLUDE \"$myheader\" %]           # 'my/misc/header'\n\nAny template directives embedded within the file will be processed accordingly. All variables\ncurrently defined will be visible and accessible from within the included template.\n\n[% title = 'Hello World' %]\n[% INCLUDE header %]\n<body>\n...\n\nheader:\n\n<html>\n<title>[% title %]</title>\n\noutput:\n\n<html>\n<title>Hello World</title>\n<body>\n...\n\nLocal variable definitions may be specified after the template name, temporarily masking any\nexisting variables. Insignificant whitespace is ignored within directives so you can add\nvariable definitions on the same line, the next line or split across several line with comments\ninterspersed, if you prefer.\n\n[% INCLUDE table %]\n\n[% INCLUDE table title=\"Active Projects\" %]\n\n[% INCLUDE table\ntitle   = \"Active Projects\"\nbgcolor = \"#80ff00\"    # chartreuse\nborder  = 2\n%]\n\nThe \"INCLUDE\" directive localises (i.e. copies) all variables before processing the template.\nAny changes made within the included template will not affect variables in the including\ntemplate.\n\n[% foo = 10 %]\n\nfoo is originally [% foo %]\n[% INCLUDE bar %]\nfoo is still [% foo %]\n\n[% BLOCK bar %]\nfoo was [% foo %]\n[% foo = 20 %]\nfoo is now [% foo %]\n[% END %]\n\noutput:\n\nfoo is originally 10\nfoo was 10\nfoo is now 20\nfoo is still 10\n\nTechnical Note: the localisation of the stash (that is, the process by which variables are\ncopied before an \"INCLUDE\" to prevent being overwritten) is only skin deep. The top-level\nvariable namespace (hash) is copied, but no attempt is made to perform a deep-copy of other\nstructures (hashes, arrays, objects, etc.) Therefore, a \"foo\" variable referencing a hash will\nbe copied to create a new \"foo\" variable but which points to the same hash array. Thus, if you\nupdate compound variables (e.g. \"foo.bar\") then you will change the original copy, regardless of\nany stash localisation. If you're not worried about preserving variable values, or you trust the\ntemplates you're including then you might prefer to use the \"PROCESS\" directive which is faster\nby virtue of not performing any localisation.\n\nYou can specify dotted variables as \"local\" variables to an \"INCLUDE\" directive. However, be\naware that because of the localisation issues explained above (if you skipped the previous\nTechnical Note above then you might want to go back and read it or skip this section too), the\nvariables might not actually be \"local\". If the first element of the variable name already\nreferences a hash array then the variable update will affect the original variable.\n\n[% foo = {\nbar = 'Baz'\n}\n%]\n\n[% INCLUDE somefile foo.bar='Boz' %]\n\n[% foo.bar %]           # Boz\n\nThis behaviour can be a little unpredictable (and may well be improved upon in a future\nversion). If you know what you're doing with it and you're sure that the variables in question\nare defined (nor not) as you expect them to be, then you can rely on this feature to implement\nsome powerful \"global\" data sharing techniques. Otherwise, you might prefer to steer well clear\nand always pass simple (undotted) variables as parameters to \"INCLUDE\" and other similar\ndirectives.\n\nIf you want to process several templates in one go then you can specify each of their names\n(quoted or unquoted names only, no unquoted $variables) joined together by \"+\". The \"INCLUDE\"\ndirective will then process them in order.\n\n[% INCLUDE html/header + \"site/$header\" + site/menu\ntitle = \"My Groovy Web Site\"\n%]\n\nThe variable stash is localised once and then the templates specified are processed in order,\nall within that same variable context. This makes it slightly faster than specifying several\nseparate \"INCLUDE\" directives (because you only clone the variable stash once instead of n\ntimes), but not quite as \"safe\" because any variable changes in the first file will be visible\nin the second, third and so on. This might be what you want, of course, but then again, it might\nnot.\n\nPROCESS\nThe PROCESS directive is similar to \"INCLUDE\" but does not perform any localisation of variables\nbefore processing the template. Any changes made to variables within the included template will\nbe visible in the including template.\n\n[% foo = 10 %]\n\nfoo is [% foo %]\n[% PROCESS bar %]\nfoo is [% foo %]\n\n[% BLOCK bar %]\n[% foo = 20 %]\nchanged foo to [% foo %]\n[% END %]\n\noutput:\n\nfoo is 10\nchanged foo to 20\nfoo is 20\n\nParameters may be specified in the \"PROCESS\" directive, but these too will become visible\nchanges to current variable values.\n\n[% foo = 10 %]\nfoo is [% foo %]\n[% PROCESS bar\nfoo = 20\n%]\nfoo is [% foo %]\n\n[% BLOCK bar %]\nthis is bar, foo is [% foo %]\n[% END %]\n\noutput:\n\nfoo is 10\nthis is bar, foo is 20\nfoo is 20\n\nThe \"PROCESS\" directive is slightly faster than \"INCLUDE\" because it avoids the need to localise\n(i.e. copy) the variable stash before processing the template. As with \"INSERT\" and \"INCLUDE\",\nthe first parameter does not need to be quoted as long as it contains only alphanumeric\ncharacters, underscores, periods or forward slashes. A \"$\" prefix can be used to explicitly\nindicate a variable which should be interpolated to provide the template name:\n\n[% myheader = 'my/misc/header' %]\n[% PROCESS  myheader %]              # 'myheader'\n[% PROCESS $myheader %]              # 'my/misc/header'\n\nAs with \"INCLUDE\", multiple templates can be specified, delimited by \"+\", and are processed in\norder.\n\n[% PROCESS html/header + my/header %]\n\nWRAPPER\nIt's not unusual to find yourself adding common headers and footers to pages or sub-sections\nwithin a page. Something like this:\n\n[% INCLUDE section/header\ntitle = 'Quantum Mechanics'\n%]\nQuantum mechanics is a very interesting subject wish\nshould prove easy for the layman to fully comprehend.\n[% INCLUDE section/footer %]\n\n[% INCLUDE section/header\ntitle = 'Desktop Nuclear Fusion for under $50'\n%]\nThis describes a simple device which generates significant\nsustainable electrical power from common tap water by process\nof nuclear fusion.\n[% INCLUDE section/footer %]\n\nThe individual template components being included might look like these:\n\nsection/header:\n\n<p>\n<h2>[% title %]</h2>\n\nsection/footer:\n\n</p>\n\nThe \"WRAPPER\" directive provides a way of simplifying this a little. It encloses a block up to a\nmatching \"END\" directive, which is first processed to generate some output. This is then passed\nto the named template file or \"BLOCK\" as the \"content\" variable.\n\n[% WRAPPER section\ntitle = 'Quantum Mechanics'\n%]\nQuantum mechanics is a very interesting subject wish\nshould prove easy for the layman to fully comprehend.\n[% END %]\n\n[% WRAPPER section\ntitle = 'Desktop Nuclear Fusion for under $50'\n%]\nThis describes a simple device which generates significant\nsustainable electrical power from common tap water by process\nof nuclear fusion.\n[% END %]\n\nThe single 'section' template can then be defined as:\n\n<h2>[% title %]</h2>\n<p>\n[% content %]\n</p>\n\nLike other block directives, it can be used in side-effect notation:\n\n[% INSERT legalese.txt WRAPPER bigboldtable %]\n\nIt's also possible to specify multiple templates to a \"WRAPPER\" directive. The specification\norder indicates outermost to innermost wrapper templates. For example, given the following\ntemplate block definitions:\n\n[% BLOCK bold   %]<b>[% content %]</b>[% END %]\n[% BLOCK italic %]<i>[% content %]</i>[% END %]\n\nthe directive\n\n[% WRAPPER bold+italic %]Hello World[% END %]\n\nwould generate the following output:\n",
                "subsections": [
                    {
                        "name": "<i>Hello World</i>",
                        "content": "BLOCK\nThe \"BLOCK\"...\"END\" construct can be used to define template component blocks which can be\nprocessed with the \"INCLUDE\", \"PROCESS\" and \"WRAPPER\" directives.\n\n[% BLOCK tabrow %]\n<tr>\n<td>[% name %]<td>\n<td>[% email %]</td>\n</tr>\n[% END %]\n\n<table>\n[% PROCESS tabrow  name='Fred'  email='fred@nowhere.com' %]\n[% PROCESS tabrow  name='Alan'  email='alan@nowhere.com' %]\n</table>\n\nA \"BLOCK\" definition can be used before it is defined, as long as the definition resides in the\nsame file. The block definition itself does not generate any output.\n\n[% PROCESS tmpblk %]\n\n[% BLOCK tmpblk %] This is OK [% END %]\n\nYou can use an anonymous \"BLOCK\" to capture the output of a template fragment.\n\n[% julius = BLOCK %]\nAnd Caesar's spirit, ranging for revenge,\nWith Ate by his side come hot from hell,\nShall in these confines with a monarch's voice\nCry  'Havoc', and let slip the dogs of war;\nThat this foul deed shall smell above the earth\nWith carrion men, groaning for burial.\n[% END %]\n\nLike a named block, it can contain any other template directives which are processed when the\nblock is defined. The output generated by the block is then assigned to the variable \"julius\".\n\nAnonymous \"BLOCK\"s can also be used to define block macros. The enclosing block is processed\neach time the macro is called.\n\n[% MACRO locate BLOCK %]\nThe [% animal %] sat on the [% place %].\n[% END %]\n\n[% locate(animal='cat', place='mat') %]    # The cat sat on the mat\n[% locate(animal='dog', place='log') %]    # The dog sat on the log\n"
                    }
                ]
            },
            "Conditional Processing": {
                "content": "IF / UNLESS / ELSIF / ELSE\nThe \"IF\" and \"UNLESS\" directives can be used to process or ignore a block based on some run-time\ncondition.\n\n[% IF frames %]\n[% INCLUDE frameset %]\n[% END %]\n\n[% UNLESS textmode %]\n[% INCLUDE biglogo %]\n[% END %]\n\nMultiple conditions may be joined with \"ELSIF\" and/or \"ELSE\" blocks.\n\n[% IF age < 10 %]\nHello [% name %], does your mother know you're\nusing her AOL account?\n[% ELSIF age < 18 %]\nSorry, you're not old enough to enter\n(and too dumb to lie about your age)\n[% ELSE %]\nWelcome [% name %].\n[% END %]\n\nThe following conditional and boolean operators may be used:\n\n== != < <= > >= && || ! and or not\n\nConditions may be arbitrarily complex and are evaluated with the same precedence as in Perl.\nParenthesis may be used to explicitly determine evaluation order.\n\n# ridiculously contrived complex example\n[% IF (name == 'admin' || uid <= 0) && mode == 'debug' %]\nI'm confused.\n[% ELSIF more > less %]\nThat's more or less correct.\n[% END %]\n\nThe \"and\", \"or\" and \"not\" operator are provided as aliases for \"&&\", \"||\" and \"!\", respectively.\nUnlike Perl, which treats \"and\", \"or\" and \"not\" as separate, lower-precedence versions of the\nother operators, the Template Toolkit performs a straightforward substitution of \"and\" for \"&&\",\nand so on. That means that \"and\", \"or\" and \"not\" have the same operator precedence as \"&&\", \"||\"\nand \"!\".\n\nSWITCH / CASE\nThe \"SWITCH\" / \"CASE\" construct can be used to perform a multi-way conditional test. The\n\"SWITCH\" directive expects an expression which is first evaluated and then compared against each\nCASE statement in turn. Each \"CASE\" directive should contain a single value or a list of values\nwhich should match. \"CASE\" may also be left blank or written as \"[% CASE DEFAULT %]\" to specify\na default match. Only one \"CASE\" matches, there is no drop-through between \"CASE\" statements.\n\n[% SWITCH myvar %]\n[%   CASE 'value1' %]\n...\n[%   CASE ['value2', 'value3'] %]   # multiple values\n...\n[%   CASE myhash.keys %]            # ditto\n...\n[%   CASE %]                        # default\n...\n[% END %]\n",
                "subsections": []
            },
            "Loop Processing": {
                "content": "FOREACH\nThe \"FOREACH\" directive will iterate through the items in a list, processing the enclosed block\nfor each one.\n\n[% foo   = 'Foo'\nitems = [ 'one', 'two', 'three' ]\n%]\n\nThings:\n[% FOREACH thing IN [ foo 'Bar' \"$foo Baz\" ] %]\n* [% thing %]\n[% END %]\n\nItems:\n[% FOREACH i IN items %]\n* [% i %]\n[% END %]\n\nStuff:\n[% stuff = [ foo \"$foo Bar\" ] %]\n[% FOREACH s IN stuff %]\n* [% s %]\n[% END %]\n\noutput:\n\nThings:\n* Foo\n* Bar\n* Foo Baz\n\nItems:\n* one\n* two\n* three\n\nStuff:\n* Foo\n* Foo Bar\n\nYou can use also use \"=\" instead of \"IN\" if you prefer.\n\n[% FOREACH i = items %]\n\nWhen the \"FOREACH\" directive is used without specifying a target variable, any iterated values\nwhich are hash references will be automatically imported.\n\n[% userlist = [\n{ id => 'tom',   name => 'Thomas'  },\n{ id => 'dick',  name => 'Richard'  },\n{ id => 'larry', name => 'Lawrence' },\n]\n%]\n\n[% FOREACH user IN userlist %]\n[% user.id %] [% user.name %]\n[% END %]\n\nshort form:\n\n[% FOREACH userlist %]\n[% id %] [% name %]\n[% END %]\n\nNote that this particular usage creates a localised variable context to prevent the imported\nhash keys from overwriting any existing variables. The imported definitions and any other\nvariables defined in such a \"FOREACH\" loop will be lost at the end of the loop, when the\nprevious context and variable values are restored.\n\nHowever, under normal operation, the loop variable remains in scope after the \"FOREACH\" loop has\nended (caveat: overwriting any variable previously in scope). This is useful as the loop\nvariable is secretly an iterator object (see below) and can be used to analyse the last entry\nprocessed by the loop.\n\nThe \"FOREACH\" directive can also be used to iterate through the entries in a hash array. Each\nentry in the hash is returned in sorted order (based on the key) as a hash array containing\n'key' and 'value' items.\n\n[% users = {\ntom   => 'Thomas',\ndick  => 'Richard',\nlarry => 'Lawrence',\n}\n%]\n\n[% FOREACH u IN users %]\n* [% u.key %] : [% u.value %]\n[% END %]\n\nOutput:\n\n* dick : Richard\n* larry : Lawrence\n* tom : Thomas\n\nThe \"NEXT\" directive starts the next iteration in the \"FOREACH\" loop.\n\n[% FOREACH user IN userlist %]\n[% NEXT IF user.isguest %]\nName: [% user.name %]    Email: [% user.email %]\n[% END %]\n\nThe \"LAST\" directive can be used to prematurely exit the loop. \"BREAK\" is also provided as an\nalias for \"LAST\".\n\n[% FOREACH match IN results.nsort('score').reverse %]\n[% LAST IF match.score < 50 %]\n[% match.score %] : [% match.url %]\n[% END %]\n\nThe \"FOREACH\" directive is implemented using the Template::Iterator module. A reference to the\niterator object for a \"FOREACH\" directive is implicitly available in the \"loop\" variable. The\nfollowing methods can be called on the \"loop\" iterator.\n\nsize()      number of elements in the list\nmax()       index number of last element (size - 1)\nindex()     index of current iteration from 0 to max()\ncount()     iteration counter from 1 to size() (i.e. index() + 1)\nfirst()     true if the current iteration is the first\nlast()      true if the current iteration is the last\nprev()      return the previous item in the list\nnext()      return the next item in the list\n\nSee Template::Iterator for further details.\n\nExample:\n\n[% FOREACH item IN [ 'foo', 'bar', 'baz' ] -%]\n[%- \"<ul>\\n\" IF loop.first %]\n<li>[% loop.count %]/[% loop.size %]: [% item %]\n[%- \"</ul>\\n\" IF loop.last %]\n[% END %]\n\nOutput:\n\n<ul>\n<li>1/3: foo\n<li>2/3: bar\n<li>3/3: baz\n</ul>\n\nNested loops will work as expected, with the \"loop\" variable correctly referencing the innermost\nloop and being restored to any previous value (i.e. an outer loop) at the end of the loop.\n\n[% FOREACH group IN grouplist;\n# loop => group iterator\n\"Groups:\\n\" IF loop.first;\n\nFOREACH user IN group.userlist;\n# loop => user iterator\n\"$loop.count: $user.name\\n\";\nEND;\n\n# loop => group iterator\n\"End of Groups\\n\" IF loop.last;\nEND\n%]\n\nThe \"iterator\" plugin can also be used to explicitly create an iterator object. This can be\nuseful within nested loops where you need to keep a reference to the outer iterator within the\ninner loop. The iterator plugin effectively allows you to create an iterator by a name other\nthan \"loop\". See Template::Plugin::Iterator for further details.\n\n[% USE giter = iterator(grouplist) %]\n\n[% FOREACH group IN giter %]\n[% FOREACH user IN group.userlist %]\nuser #[% loop.count %] in\ngroup [% giter.count %] is\nnamed [% user.name %]\n[% END %]\n[% END %]\n\nWHILE\nThe \"WHILE\" directive can be used to repeatedly process a template block while a conditional\nexpression evaluates true. The expression may be arbitrarily complex as per \"IF\" / \"UNLESS\".\n\n[% WHILE total < 100 %]\n...\n[% total = calculatenewtotal %]\n[% END %]\n\nAn assignment can be enclosed in parenthesis to evaluate the assigned value.\n\n[% WHILE (user = getnextuserrecord) %]\n[% user.name %]\n[% END %]\n\nThe \"NEXT\" directive can be used to start the next iteration of a \"WHILE\" loop and \"BREAK\" can\nbe used to exit the loop, both as per \"FOREACH\".\n\nThe Template Toolkit uses a failsafe counter to prevent runaway \"WHILE\" loops which would\notherwise never terminate. If the loop exceeds 1000 iterations then an \"undef\" exception will be\nthrown, reporting the error:\n\nWHILE loop terminated (> 1000 iterations)\n\nThe $Template::Directive::WHILEMAX variable controls this behaviour and can be set to a higher\nvalue if necessary.\n",
                "subsections": []
            },
            "Filters, Plugins, Macros and Perl": {
                "content": "FILTER\nThe \"FILTER\" directive can be used to post-process the output of a block. A number of standard\nfilters are provided with the Template Toolkit. The \"html\" filter, for example, escapes the '<',\n'>' and '&' characters to prevent them from being interpreted as HTML tags or entity reference\nmarkers.\n\n[% FILTER html %]\nHTML text may have < and > characters embedded\nwhich you want converted to the correct HTML entities.\n[% END %]\n\noutput:\n\nHTML text may have &lt; and &gt; characters embedded\nwhich you want converted to the correct HTML entities.\n\nThe \"FILTER\" directive can also follow various other non-block directives. For example:\n\n[% INCLUDE mytext FILTER html %]\n\nThe \"|\" character can also be used as an alias for \"FILTER\".\n\n[% INCLUDE mytext | html %]\n\nMultiple filters can be chained together and will be called in sequence.\n\n[% INCLUDE mytext FILTER html FILTER htmlpara %]\n\nor\n\n[% INCLUDE mytext | html | htmlpara %]\n\nFilters come in two flavours, known as 'static' or 'dynamic'. A static filter is a simple\nsubroutine which accepts a text string as the only argument and returns the modified text. The\n\"html\" filter is an example of a static filter, implemented as:\n\nsub htmlfilter {\nmy $text = shift;\nfor ($text) {\ns/&/&amp;/g;\ns/</&lt;/g;\ns/>/&gt;/g;\n}\nreturn $text;\n}\n\nDynamic filters can accept arguments which are specified when the filter is called from a\ntemplate. The \"repeat\" filter is such an example, accepting a numerical argument which specifies\nthe number of times that the input text should be repeated.\n\n[% FILTER repeat(3) %]blah [% END %]\n\noutput:\n\nblah blah blah\n\nThese are implemented as filter 'factories'. The factory subroutine is passed a reference to the\ncurrent Template::Context object along with any additional arguments specified. It should then\nreturn a subroutine reference (e.g. a closure) which implements the filter. The \"repeat\" filter\nfactory is implemented like this:\n\nsub repeatfilterfactory {\nmy ($context, $iter) = @;\n$iter = 1 unless defined $iter;\n\nreturn sub {\nmy $text = shift;\n$text = '' unless defined $text;\nreturn join('\\n', $text) x $iter;\n}\n}\n\nThe \"FILTERS\" option, described in Template::Manual::Config, allows custom filters to be defined\nwhen a Template object is instantiated. The definefilter() method allows further filters to be\ndefined at any time.\n\nWhen using a filter, it is possible to assign an alias to it for further use. This is most\nuseful for dynamic filters that you want to re-use with the same configuration.\n\n[% FILTER echo = repeat(2) %]\nIs there anybody out there?\n[% END %]\n\n[% FILTER echo %]\nMother, should I build a wall?\n[% END %]\n\nOutput:\n\nIs there anybody out there?\nIs there anybody out there?\n\nMother, should I build a wall?\nMother, should I build a wall?\n\nThe \"FILTER\" directive automatically quotes the name of the filter. As with \"INCLUDE\" et al, you\ncan use a variable to provide the name of the filter, prefixed by \"$\".\n\n[% myfilter = 'html' %]\n[% FILTER $myfilter %]      # same as [% FILTER html %]\n...\n[% END %]\n\nA template variable can also be used to define a static filter subroutine. However, the Template\nToolkit will automatically call any subroutine bound to a variable and use the value returned.\nThus, the above example could be implemented as:\n\nmy $vars = {\nmyfilter => sub { return 'html' },\n};\n\ntemplate:\n\n[% FILTER $myfilter %]      # same as [% FILTER html %]\n...\n[% END %]\n\nTo define a template variable that evaluates to a subroutine reference that can be used by the\n\"FILTER\" directive, you should create a subroutine that, when called automatically by the\nTemplate Toolkit, returns another subroutine reference which can then be used to perform the\nfilter operation. Note that only static filters can be implemented in this way.\n\nmy $vars = {\nmyfilter => sub { \\&myfiltersub },\n};\n\nsub myfiltersub {\nmy $text = shift;\n# do something\nreturn $text;\n}\n\ntemplate:\n\n[% FILTER $myfilter %]\n...\n[% END %]\n\nAlternately, you can bless a subroutine reference into a class (any class will do) to fool the\nTemplate Toolkit into thinking it's an object rather than a subroutine. This will then bypass\nthe automatic \"call-a-subroutine-to-return-a-value\" magic.\n\nmy $vars = {\nmyfilter => bless(\\&myfiltersub, 'anythingyoulike'),\n};\n\ntemplate:\n\n[% FILTER $myfilter %]\n...\n[% END %]\n\nFilters bound to template variables remain local to the variable context in which they are\ndefined. That is, if you define a filter in a \"PERL\" block within a template that is loaded via\n\"INCLUDE\", then the filter definition will only exist until the end of that template when the\nstash is delocalised, restoring the previous variable state. If you want to define a filter\nwhich persists for the lifetime of the processor, or define additional dynamic filter factories,\nthen you can call the definefilter() method on the current Template::Context object.\n\nSee Template::Manual::Filters for a complete list of available filters, their descriptions and\nexamples of use.\n\nUSE\nThe \"USE\" directive can be used to load and initialise \"plugin\" extension modules.\n\n[% USE myplugin %]\n\nA plugin is a regular Perl module that conforms to a particular object-oriented interface,\nallowing it to be loaded into and used automatically by the Template Toolkit. For details of\nthis interface and information on writing plugins, consult Template::Plugin.\n\nA number of standard plugins are included with the Template Toolkit (see below and\nTemplate::Manual::Plugins). The names of these standard plugins are case insensitive.\n\n[% USE CGI   %]        # => Template::Plugin::CGI\n[% USE Cgi   %]        # => Template::Plugin::CGI\n[% USE cgi   %]        # => Template::Plugin::CGI\n\nYou can also define further plugins using the \"PLUGINS\" option.\n\nmy $tt = Template->new({\nPLUGINS => {\nfoo => 'My::Plugin::Foo',\nbar => 'My::Plugin::Bar',\n},\n});\n\nThe recommended convention is to specify these plugin names in lower case. The Template Toolkit\nfirst looks for an exact case-sensitive match and then tries the lower case conversion of the\nname specified.\n\n[% USE Foo %]      # look for 'Foo' then 'foo'\n\nIf you define all your \"PLUGINS\" with lower case names then they will be located regardless of\nhow the user specifies the name in the \"USE\" directive. If, on the other hand, you define your\n\"PLUGINS\" with upper or mixed case names then the name specified in the \"USE\" directive must\nmatch the case exactly.\n\nIf the plugin isn't defined in either the standard plugins ($Template::Plugins::STDPLUGINS) or\nvia the \"PLUGINS\" option, then the \"PLUGINBASE\" is searched.\n\nIn this case the plugin name *is* case-sensitive. It is appended to each of the \"PLUGINBASE\"\nmodule namespaces in turn (default: \"Template::Plugin\") to construct a full module name which it\nattempts to locate and load. Any periods, '\".\"', in the name will be converted to '\"::\"'.\n\n[% USE MyPlugin %]     #  => Template::Plugin::MyPlugin\n[% USE Foo.Bar  %]     #  => Template::Plugin::Foo::Bar\n\nThe \"LOADPERL\" option (disabled by default) provides a further way by which external Perl\nmodules may be loaded. If a regular Perl module (i.e. not a \"Template::Plugin::*\" or other\nmodule relative to some \"PLUGINBASE\") supports an object-oriented interface and a \"new()\"\nconstructor then it can be loaded and instantiated automatically. The following trivial example\nshows how the IO::File module might be used.\n\n[% USE file = IO.File('/tmp/mydata') %]\n\n[% WHILE (line = file.getline) %]\n<!-- [% line %] -->\n[% END %]\n\nAny additional parameters supplied in parenthesis after the plugin name will be also be passed\nto the \"new()\" constructor. A reference to the current Template::Context object is passed as the\nfirst parameter.\n\n[% USE MyPlugin('foo', 123) %]\n\nequivalent to:\n\nTemplate::Plugin::MyPlugin->new($context, 'foo', 123);\n\nThe only exception to this is when a module is loaded via the \"LOADPERL\" option. In this case\nthe $context reference is *not* passed to the \"new()\" constructor. This is based on the\nassumption that the module is a regular Perl module rather than a Template Toolkit plugin so\nisn't expecting a context reference and wouldn't know what to do with it anyway.\n\nNamed parameters may also be specified. These are collated into a hash which is passed by\nreference as the last parameter to the constructor, as per the general code calling interface.\n\n[% USE url('/cgi-bin/foo', mode='submit', debug=1) %]\n\nequivalent to:\n\nTemplate::Plugin::URL->new(\n$context,\n'/cgi-bin/foo'\n{ mode => 'submit', debug => 1 }\n);\n\nThe plugin may represent any data type; a simple variable, hash, list or code reference, but in\nthe general case it will be an object reference. Methods can be called on the object (or the\nrelevant members of the specific data type) in the usual way:\n\n[% USE table(mydata, rows=3) %]\n\n[% FOREACH row IN table.rows %]\n<tr>\n[% FOREACH item IN row %]\n<td>[% item %]</td>\n[% END %]\n</tr>\n[% END %]\n\nAn alternative name may be provided for the plugin by which it can be referenced:\n\n[% USE scores = table(myscores, cols=5) %]\n\n[% FOREACH row IN scores.rows %]\n...\n[% END %]\n\nYou can use this approach to create multiple plugin objects with different configurations. This\nexample shows how the format plugin is used to create sub-routines bound to variables for\nformatting text as per \"printf()\".\n\n[% USE bold = format('<b>%s</b>') %]\n[% USE ital = format('<i>%s</i>') %]\n[% bold('This is bold')   %]\n[% ital('This is italic') %]\n\nOutput:\n",
                "subsections": [
                    {
                        "name": "This is bold",
                        "content": "<i>This is italic</i>\n\nThis next example shows how the URL plugin can be used to build dynamic URLs from a base part\nand optional query parameters.\n\n[% USE mycgi = URL('/cgi-bin/foo.pl', debug=1) %]\n<a href=\"[% mycgi %]\">...\n<a href=\"[% mycgi(mode='submit') %]\"...\n\nOutput:\n\n<a href=\"/cgi-bin/foo.pl?debug=1\">...\n<a href=\"/cgi-bin/foo.pl?mode=submit&debug=1\">...\n\nThe CGI plugin is an example of one which delegates to another Perl module. In this case, to\nLincoln Stein's \"CGI\" module. All of the methods provided by the \"CGI\" module are available via\nthe plugin.\n\n[% USE CGI;\nCGI.startform;\nCGI.checkboxgroup( name   = 'colours',\nvalues = [ 'red' 'green' 'blue' ] );\nCGI.popupmenu( name   = 'items',\nvalues = [ 'foo' 'bar' 'baz' ] );\nCGI.endform\n%]\n\nSee Template::Manual::Plugins for more information on the plugins distributed with the toolkit\nor available from CPAN.\n\nMACRO\nThe \"MACRO\" directive allows you to define a directive or directive block which is then\nevaluated each time the macro is called.\n\n[% MACRO header INCLUDE header %]\n\nCalling the macro as:\n\n[% header %]\n\nis then equivalent to:\n\n[% INCLUDE header %]\n\nMacros can be passed named parameters when called. These values remain local to the macro.\n\n[% header(title='Hello World') %]\n\nequivalent to:\n\n[% INCLUDE header title='Hello World' %]\n\nA \"MACRO\" definition may include parameter names. Values passed to the macros are then mapped to\nthese local variables. Other named parameters may follow these.\n\n[% MACRO header(title) INCLUDE header %]\n[% header('Hello World') %]\n[% header('Hello World', bgcol='#123456') %]\n\nequivalent to:\n\n[% INCLUDE header title='Hello World' %]\n[% INCLUDE header title='Hello World' bgcol='#123456' %]\n\nHere's another example, defining a macro for display numbers in comma-delimited groups of 3,\nusing the chunk and join virtual method.\n\n[% MACRO number(n) GET n.chunk(-3).join(',') %]\n[% number(1234567) %]    # 1,234,567\n\nA \"MACRO\" may precede any directive and must conform to the structure of the directive.\n\n[% MACRO header IF frames %]\n[% INCLUDE frames/header %]\n[% ELSE %]\n[% INCLUDE header %]\n[% END %]\n\n[% header %]\n\nA \"MACRO\" may also be defined as an anonymous \"BLOCK\". The block will be evaluated each time the\nmacro is called.\n\n[% MACRO header BLOCK %]\n...content...\n[% END %]\n\n[% header %]\n\nIf you've got the \"EVALPERL\" option set, then you can even define a \"MACRO\" as a \"PERL\" block\n(see below):\n\n[% MACRO triple(n) PERL %]\nmy $n = $stash->get('n');\nprint $n * 3;\n[% END -%]\n\nPERL\n(for the advanced reader)\n\nThe \"PERL\" directive is used to mark the start of a block which contains Perl code for\nevaluation. The \"EVALPERL\" option must be enabled for Perl code to be evaluated or a \"perl\"\nexception will be thrown with the message '\"EVALPERL not set\"'.\n\nPerl code is evaluated in the \"Template::Perl\" package. The $context package variable contains a\nreference to the current Template::Context object. This can be used to access the functionality\nof the Template Toolkit to process other templates, load plugins, filters, etc. See\nTemplate::Context for further details.\n\n[% PERL %]\nprint $context->include('myfile');\n[% END %]\n\nThe $stash variable contains a reference to the top-level stash object which manages template\nvariables. Through this, variable values can be retrieved and updated. See Template::Stash for\nfurther details.\n\n[% PERL %]\n$stash->set(foo => 'bar');\nprint \"foo value: \", $stash->get('foo');\n[% END %]\n\nOutput:\n\nfoo value: bar\n\nOutput is generated from the \"PERL\" block by calling \"print()\". Note that the\n\"Template::Perl::PERLOUT\" handle is selected (tied to an output buffer) instead of \"STDOUT\".\n\n[% PERL %]\nprint \"foo\\n\";                           # OK\nprint PERLOUT \"bar\\n\";                   # OK, same as above\nprint Template::Perl::PERLOUT \"baz\\n\";   # OK, same as above\nprint STDOUT \"qux\\n\";                    # WRONG!\n[% END %]\n\nThe \"PERL\" block may contain other template directives. These are processed before the Perl code\nis evaluated.\n\n[% name = 'Fred Smith' %]\n\n[% PERL %]\nprint \"[% name %]\\n\";\n[% END %]\n\nThus, the Perl code in the above example is evaluated as:\n\nprint \"Fred Smith\\n\";\n\nExceptions may be thrown from within \"PERL\" blocks using \"die()\". They will be correctly caught\nby enclosing \"TRY\" blocks.\n\n[% TRY %]\n[% PERL %]\ndie \"nothing to live for\\n\";\n[% END %]\n[% CATCH %]\nerror: [% error.info %]\n[% END %]\n\noutput: error: nothing to live for\n\nRAWPERL\n(for the very advanced reader)\n\nThe Template Toolkit parser reads a source template and generates the text of a Perl subroutine\nas output. It then uses \"eval()\" to evaluate it into a subroutine reference. This subroutine is\nthen called to process the template, passing a reference to the current Template::Context object\nthrough which the functionality of the Template Toolkit can be accessed. The subroutine\nreference can be cached, allowing the template to be processed repeatedly without requiring any\nfurther parsing.\n\nFor example, a template such as:\n\n[% PROCESS header %]\nThe [% animal %] sat on the [% location %]\n[% PROCESS footer %]\n\nis converted into the following Perl subroutine definition:\n\nsub {\nmy $context = shift;\nmy $stash   = $context->stash;\nmy $output  = '';\nmy $error;\n\neval { BLOCK: {\n$output .=  $context->process('header');\n$output .=  \"The \";\n$output .=  $stash->get('animal');\n$output .=  \" sat on the \";\n$output .=  $stash->get('location');\n$output .=  $context->process('footer');\n$output .=  \"\\n\";\n} };\nif ($@) {\n$error = $context->catch($@, \\$output);\ndie $error unless $error->type eq 'return';\n}\n\nreturn $output;\n}\n\nTo examine the Perl code generated, such as in the above example, set the\n$Template::Parser::DEBUG package variable to any true value. You can also set the\n$Template::Directive::PRETTY variable true to have the code formatted in a readable manner for\nhuman consumption. The source code for each generated template subroutine will be printed to\n\"STDERR\" on compilation (i.e. the first time a template is used).\n\n$Template::Parser::DEBUG = 1;\n$Template::Directive::PRETTY = 1;\n\n$template->process($file, $vars)\n|| die $template->error(), \"\\n\";\n\nThe \"PERL\" ... \"END\" construct allows Perl code to be embedded into a template when the\n\"EVALPERL\" option is set. It is evaluated at \"runtime\" using \"eval()\" each time the template\nsubroutine is called. This is inherently flexible, but not as efficient as it could be,\nespecially in a persistent server environment where a template may be processed many times.\n\nThe \"RAWPERL\" directive allows you to write Perl code that is integrated directly into the\ngenerated Perl subroutine text. It is evaluated once at compile time and is stored in cached\nform as part of the compiled template subroutine. This makes \"RAWPERL\" blocks more efficient\nthan \"PERL\" blocks.\n\nThe downside is that you must code much closer to the metal. For example, in a \"PERL\" block you\ncan call print() to generate some output. \"RAWPERL\" blocks don't afford such luxury. The code is\ninserted directly into the generated subroutine text and should conform to the convention of\nappending to the $output variable.\n\n[% PROCESS  header %]\n\n[% RAWPERL %]\n$output .= \"Some output\\n\";\n...\n$output .= \"Some more output\\n\";\n[% END %]\n\nThe critical section of the generated subroutine for this example would then look something\nlike:\n\n...\neval { BLOCK: {\n$output .=  $context->process('header');\n$output .=  \"\\n\";\n$output .= \"Some output\\n\";\n...\n$output .= \"Some more output\\n\";\n$output .=  \"\\n\";\n} };\n...\n\nAs with \"PERL\" blocks, the $context and $stash references are pre-defined and available for use\nwithin \"RAWPERL\" code.\n"
                    }
                ]
            },
            "Exception Handling and Flow Control": {
                "content": "TRY / THROW / CATCH / FINAL\n(more advanced material)\n\nThe Template Toolkit supports fully functional, nested exception handling. The \"TRY\" directive\nintroduces an exception handling scope which continues until the matching \"END\" directive. Any\nerrors that occur within that block will be caught and can be handled by one of the \"CATCH\"\nblocks defined.\n\n[% TRY %]\n...blah...blah...\n[% CALL somecode %]\n...etc...\n[% INCLUDE someblock %]\n...and so on...\n[% CATCH %]\nAn error occurred!\n[% END %]\n\nErrors are raised as exceptions (objects of the Template::Exception class) which contain two\nfields: \"type\" and \"info\". The exception \"type\" is used to indicate the kind of error that\noccurred. It is a simple text string which can contain letters, numbers, '\"\"' or '\".\"'. The\n\"info\" field contains an error message indicating what actually went wrong. Within a catch\nblock, the exception object is aliased to the \"error\" variable. You can access the \"type\" and\n\"info\" fields directly.\n\n[% mydsn = 'dbi:MySQL:foobar' %]\n...\n\n[% TRY %]\n[% USE DBI(mydsn) %]\n[% CATCH %]\nERROR! Type: [% error.type %]\nInfo: [% error.info %]\n[% END %]\n\noutput (assuming a non-existent database called '\"foobar\"'):\n\nERROR!  Type: DBI\nInfo: Unknown database \"foobar\"\n\nThe \"error\" variable can also be specified by itself and will return a string of the form\n\"\"$type error - $info\"\".\n\n...\n[% CATCH %]\nERROR: [% error %]\n[% END %]\n\nOutput:\n\nERROR: DBI error - Unknown database \"foobar\"\n\nEach \"CATCH\" block may be specified with a particular exception type denoting the kind of error\nthat it should catch. Multiple \"CATCH\" blocks can be provided to handle different types of\nexception that may be thrown in the \"TRY\" block. A \"CATCH\" block specified without any type, as\nin the previous example, is a default handler which will catch any otherwise uncaught\nexceptions. This can also be specified as \"[% CATCH DEFAULT %]\".\n\n[% TRY %]\n[% INCLUDE myfile %]\n[% USE DBI(mydsn) %]\n[% CALL somecode %]\n[% CATCH file %]\nFile Error! [% error.info %]\n[% CATCH DBI %]\n[% INCLUDE database/error.html %]\n[% CATCH %]\n[% error %]\n[% END %]\n\nRemember that you can specify multiple directives within a single tag, each delimited by '\";\"'.\nSo the above example can be written more concisely as:\n\n[% TRY;\nINCLUDE myfile;\nUSE DBI(mydsn);\nCALL somecode;\nCATCH file;\n\"File Error! $error.info\";\nCATCH DBI;\nINCLUDE database/error.html;\nCATCH;\nerror;\nEND\n%]\n\nThe \"DBI\" plugin throws exceptions of the \"DBI\" type (in case that wasn't already obvious). The\nother specific exception caught here is of the \"file\" type.\n\nA \"file\" exception is automatically thrown by the Template Toolkit when it can't find a file, or\nfails to load, parse or process a file that has been requested by an \"INCLUDE\", \"PROCESS\",\n\"INSERT\" or \"WRAPPER\" directive. If \"myfile\" can't be found in the example above, the \"[%\nINCLUDE myfile %]\" directive will raise a \"file\" exception which is then caught by the \"[% CATCH\nfile %]\" block. The output generated would be:\n\nFile Error! myfile: not found\n\nNote that the \"DEFAULT\" option (disabled by default) allows you to specify a default file to be\nused any time a template file can't be found. This will prevent file exceptions from ever being\nraised when a non-existent file is requested (unless, of course, the \"DEFAULT\" file your specify\ndoesn't exist). Errors encountered once the file has been found (i.e. read error, parse error)\nwill be raised as file exceptions as per usual.\n\nUncaught exceptions (i.e. if the \"TRY\" block doesn't have a type specific or default \"CATCH\"\nhandler) may be caught by enclosing \"TRY\" blocks which can be nested indefinitely across\nmultiple templates. If the error isn't caught at any level then processing will stop and the\nTemplate process() method will return a false value to the caller. The relevant\nTemplate::Exception object can be retrieved by calling the error() method.\n\n[% TRY %]\n...\n[% TRY %]\n[% INCLUDE $user.header %]\n[% CATCH file %]\n[% INCLUDE header %]\n[% END %]\n...\n[% CATCH DBI %]\n[% INCLUDE database/error.html %]\n[% END %]\n\nIn this example, the inner \"TRY\" block is used to ensure that the first \"INCLUDE\" directive\nworks as expected. We're using a variable to provide the name of the template we want to\ninclude, \"user.header\", and it's possible this contains the name of a non-existent template, or\nperhaps one containing invalid template directives. If the \"INCLUDE\" fails with a \"file\" error\nthen we \"CATCH\" it in the inner block and \"INCLUDE\" the default \"header\" file instead. Any \"DBI\"\nerrors that occur within the scope of the outer \"TRY\" block will be caught in the relevant\n\"CATCH\" block, causing the \"database/error.html\" template to be processed. Note that included\ntemplates inherit all currently defined template variable so these error files can quite happily\naccess the <error> variable to retrieve information about the currently caught exception. For\nexample, the \"database/error.html\" template might look like this:\n\n<h2>Database Error</h2>\nA database error has occurred: [% error.info %]\n\nYou can also specify a \"FINAL\" block. This is always processed regardless of the outcome of the\n\"TRY\" and/or \"CATCH\" blocks. If an exception is uncaught then the \"FINAL\" block is processed\nbefore jumping to the enclosing block or returning to the caller.\n\n[% TRY %]\n...\n[% CATCH this %]\n...\n[% CATCH that %]\n...\n[% FINAL %]\nAll done!\n[% END %]\n\nThe output from the \"TRY\" block is left intact up to the point where an exception occurs. For\nexample, this template:\n\n[% TRY %]\nThis gets printed\n[% THROW food 'carrots' %]\nThis doesn't\n[% CATCH food %]\nculinary delights: [% error.info %]\n[% END %]\n\ngenerates the following output:\n\nThis gets printed\nculinary delights: carrots\n\nThe \"CLEAR\" directive can be used in a \"CATCH\" or \"FINAL\" block to clear any output created in\nthe \"TRY\" block.\n\n[% TRY %]\nThis gets printed\n[% THROW food 'carrots' %]\nThis doesn't\n[% CATCH food %]\n[% CLEAR %]\nculinary delights: [% error.info %]\n[% END %]\n\nOutput:\n\nculinary delights: carrots\n\nException types are hierarchical, with each level being separated by the familiar dot operator.\nA \"DBI.connect\" exception is a more specific kind of \"DBI\" error. Similarly, an\n\"example.error.barf\" is a more specific kind of \"example.error\" type which itself is also a\n\"example\" error.\n\nA \"CATCH\" handler that specifies a general exception type (such as \"DBI\" or \"example.error\")\nwill also catch more specific types that have the same prefix as long as a more specific handler\nisn't defined. Note that the order in which \"CATCH\" handlers are defined is irrelevant; a more\nspecific handler will always catch an exception in preference to a more generic or default one.\n\n[% TRY %]\n...\n[% CATCH DBI ;\nINCLUDE database/error.html ;\nCATCH DBI.connect ;\nINCLUDE database/connect.html ;\nCATCH ;\nINCLUDE error.html ;\nEND\n%]\n\nIn this example, a \"DBI.connect\" error has it's own handler, a more general \"DBI\" block is used\nfor all other \"DBI\" or \"DBI.*\" errors and a default handler catches everything else.\n\nExceptions can be raised in a template using the \"THROW\" directive. The first parameter is the\nexception type which doesn't need to be quoted (but can be, it's the same as \"INCLUDE\") followed\nby the relevant error message which can be any regular value such as a quoted string, variable,\netc.\n\n[% THROW food \"Missing ingredients: $recipe.error\" %]\n[% THROW user.login 'no user id: please login' %]\n[% THROW $myerror.type \"My Error: $myerror.info\" %]\n\nIt's also possible to specify additional positional or named parameters to the \"THROW\" directive\nif you want to pass more than just a simple message back as the error info field.\n\n[% THROW food 'eggs' 'flour' msg='Missing Ingredients' %]\n\nIn this case, the error \"info\" field will be a hash array containing the named arguments and an\n\"args\" item which contains a list of the positional arguments.\n\ntype => 'food',\ninfo => {\nmsg  => 'Missing Ingredients',\nargs => ['eggs', 'flour'],\n}\n\nIn addition to specifying individual positional arguments as \"[% error.info.args.n %]\", the\n\"info\" hash contains keys directly pointing to the positional arguments, as a convenient\nshortcut.\n\n[% error.info.0 %]   # same as [% error.info.args.0 %]\n\nExceptions can also be thrown from Perl code which you've bound to template variables, or\ndefined as a plugin or other extension. To raise an exception, call \"die()\" passing a reference\nto a Template::Exception object as the argument. This will then be caught by any enclosing \"TRY\"\nblocks from where the code was called.\n\nuse Template::Exception;\n...\nmy $vars = {\nfoo => sub {\n# ... do something ...\ndie Template::Exception->new('myerr.naughty',\n'Bad, bad error');\n},\n};\n\nTemplate:\n\n[% TRY %]\n[% foo %]\n[% CATCH myerr ;\n\"Error: $error\" ;\nEND\n%]\n\nOutput:\n\nError: myerr.naughty error - Bad, bad error\n\nThe \"info\" field can also be a reference to another object or data structure, if required.\n\ndie Template::Exception->new('myerror', {\nmodule => 'foo.pl',\nerrors => [ 'bad permissions', 'naughty boy' ],\n});\n\nLater, in a template:\n\n[% TRY %]\n...\n[% CATCH myerror %]\n[% error.info.errors.size or 'no';\nerror.info.errors.size == 1 ? ' error' : ' errors' %]\nin [% error.info.module %]:\n[% error.info.errors.join(', ') %].\n[% END %]\n\nGenerating the output:\n\n2 errors in foo.pl:\nbad permissions, naughty boy.\n\nYou can also call \"die()\" with a single string, as is common in much existing Perl code. This\nwill automatically be converted to an exception of the '\"undef\"' type (that's the literal string\n'\"undef\"', not the undefined value). If the string isn't terminated with a newline then Perl\nwill append the familiar \" at $file line $line\" message.\n\nsub foo {\n# ... do something ...\ndie \"I'm sorry, Dave, I can't do that\\n\";\n}\n\nIf you're writing a plugin, or some extension code that has the current Template::Context in\nscope (you can safely skip this section if this means nothing to you) then you can also raise an\nexception by calling the context throw() method. You can pass it an Template::Exception object\nreference, a pair of \"($type, $info)\" parameters or just an $info string to create an exception\nof '\"undef\"' type.\n\n$context->throw($e);            # exception object\n$context->throw('Denied');      # 'undef' type\n$context->throw('user.passwd', 'Bad Password');\n\nNEXT\nThe \"NEXT\" directive can be used to start the next iteration of a \"FOREACH\" or \"WHILE\" loop.\n\n[% FOREACH user IN users %]\n[% NEXT IF user.isguest %]\nName: [% user.name %]    Email: [% user.email %]\n[% END %]\n\nLAST\nThe \"LAST\" directive can be used to prematurely exit a \"FOREACH\" or \"WHILE\" loop.\n\n[% FOREACH user IN users %]\nName: [% user.name %]    Email: [% user.email %]\n[% LAST IF some.condition %]\n[% END %]\n\n\"BREAK\" can also be used as an alias for \"LAST\".\n\nRETURN\nThe \"RETURN\" directive can be used to stop processing the current template and return to the\ntemplate from which it was called, resuming processing at the point immediately after the\n\"INCLUDE\", \"PROCESS\" or \"WRAPPER\" directive. If there is no enclosing template then the Template",
                "subsections": [
                    {
                        "name": "process",
                        "content": "Before\n[% INCLUDE halfwit %]\nAfter\n\n[% BLOCK halfwit %]\nThis is just half...\n[% RETURN %]\n...a complete block\n[% END %]\n\nOutput:\n\nBefore\nThis is just half...\nAfter\n\nSTOP\nThe \"STOP\" directive can be used to indicate that the processor should stop gracefully without\nprocessing any more of the template document. This is a planned stop and the Template process()\nmethod will return a true value to the caller. This indicates that the template was processed\nsuccessfully according to the directives within it.\n\n[% IF something.terrible.happened %]\n[% INCLUDE fatal/error.html %]\n[% STOP %]\n[% END %]\n\n[% TRY %]\n[% USE DBI(mydsn) %]\n...\n[% CATCH DBI.connect %]\n<h1>Cannot connect to the database: [% error.info %]</h1>\n<p>\nWe apologise for the inconvenience.\n</p>\n[% INCLUDE footer %]\n[% STOP %]\n[% END %]\n\nCLEAR\nThe \"CLEAR\" directive can be used to clear the output buffer for the current enclosing block. It\nis most commonly used to clear the output generated from a \"TRY\" block up to the point where the\nerror occurred.\n\n[% TRY %]\nblah blah blah            # this is normally left intact\n[% THROW some 'error' %]  # up to the point of error\n...\n[% CATCH %]\n[% CLEAR %]               # clear the TRY output\n[% error %]               # print error string\n[% END %]\n"
                    }
                ]
            },
            "Miscellaneous": {
                "content": "META\nThe \"META\" directive allows simple metadata items to be defined within a template. These are\nevaluated when the template is parsed and as such may only contain simple values (e.g. it's not\npossible to interpolate other variables values into \"META\" variables).\n\n[% META\ntitle   = 'The Cat in the Hat'\nauthor  = 'Dr. Seuss'\nversion = 1.23\n%]\n\nThe \"template\" variable contains a reference to the main template being processed. These\nmetadata items may be retrieved as attributes of the template.\n\n<h1>[% template.title %]</h1>\n<h2>[% template.author %]</h2>\n\nThe \"name\" and \"modtime\" metadata items are automatically defined for each template to contain\nits name and modification time in seconds since the epoch.\n\n[% USE date %]              # use Date plugin to format time\n...\n[% template.name %] last modified\nat [% date.format(template.modtime) %]\n\nThe \"PREPROCESS\" and \"POSTPROCESS\" options allow common headers and footers to be added to all\ntemplates. The \"template\" reference is correctly defined when these templates are processed,\nallowing headers and footers to reference metadata items from the main template.\n\n$template = Template->new({\nPREPROCESS  => 'header',\nPOSTPROCESS => 'footer',\n});\n\n$template->process('catinhat');\n\nheader:\n\n<html>\n<head>\n<title>[% template.title %]</title>\n</head>\n<body>\n\ncatinhat:\n\n[% META\ntitle   = 'The Cat in the Hat'\nauthor  = 'Dr. Seuss'\nversion = 1.23\nyear    = 2000\n%]\n\nThe cat in the hat sat on the mat.\n\nfooter:\n\n<hr>\n&copy; [% template.year %] [% template.author %]\n</body>\n</html>\n\nThe output generated from the above example is:\n\n<html>\n<head>\n<title>The Cat in the Hat</title>\n</head>\n<body>\nThe cat in the hat sat on the mat.\n<hr>\n&copy; 2000 Dr. Seuss\n</body>\n</html>\n\nTAGS\nThe \"TAGS\" directive can be used to set the \"STARTTAG\" and \"ENDTAG\" values on a per-template\nfile basis.\n\n[% TAGS <+ +> %]\n\n<+ INCLUDE header +>\n\nThe TAGS directive may also be used to set a named \"TAGSTYLE\"\n\n[% TAGS html %]\n<!-- INCLUDE header -->\n\nSee the TAGS and TAGSTYLE configuration options for further details.\n\nDEBUG\nThe \"DEBUG\" directive can be used to enable or disable directive debug messages within a\ntemplate. The \"DEBUG\" configuration option must be set to include \"DEBUGDIRS\" for the \"DEBUG\"\ndirectives to have any effect. If \"DEBUGDIRS\" is not set then the parser will automatically\nignore and remove any \"DEBUG\" directives.\n\nThe \"DEBUG\" directive can be used with an \"on\" or \"off\" parameter to enable or disable directive\ndebugging messages from that point forward. When enabled, the output of each directive in the\ngenerated output will be prefixed by a comment indicate the file, line and original directive\ntext.\n\n[% DEBUG on %]\ndirective debugging is on (assuming DEBUG option is set true)\n[% DEBUG off %]\ndirective debugging is off\n\nThe \"format\" parameter can be used to change the format of the debugging message.\n\n[% DEBUG format '<!-- $file line $line : [% $text %] -->' %]\n",
                "subsections": []
            }
        }
    }
}