{
    "mode": "perldoc",
    "parameter": "Template::Manual::Variables",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Template%3A%3AManual%3A%3AVariables/json",
    "generated": "2026-06-10T09:58:12Z",
    "sections": {
        "NAME": {
            "content": "Template::Manual::Variables - Template variables and code bindings\n",
            "subsections": []
        },
        "Template Variables": {
            "content": "A reference to a hash array may be passed as the second argument to the process() method,\ncontaining definitions of template variables. The \"VARIABLES\" (a.k.a. \"PREDEFINE\") option can\nalso be used to pre-define variables for all templates processed by the object.\n\nmy $tt = Template->new({\nVARIABLES => {\nversion => 3.14,\nrelease => 'Sahara',\n},\n});\n\nmy $vars = {\nserialno => 271828,\n};\n\n$tt->process('myfile', $vars);\n\nmyfile template:\n\nThis is version [% version %] ([% release %]).\nSerial number: [% serialno %]\n\nGenerated Output:\n\nThis is version 3.14 (Sahara)\nSerial number: 271828\n\nVariable names may contain any alphanumeric characters or underscores. They may be lower, upper\nor mixed case although the usual convention is to use lower case. The case *is* significant\nhowever, and '\"foo\"', '\"Foo\"' and '\"FOO\"' are all different variables. Upper case variable names\nare permitted, but not recommended due to a possible conflict with an existing or future\nreserved word. As of version 2.00, these are:\n\nGET CALL SET DEFAULT INSERT INCLUDE PROCESS WRAPPER\nIF UNLESS ELSE ELSIF FOR FOREACH WHILE SWITCH CASE\nUSE PLUGIN FILTER MACRO PERL RAWPERL BLOCK META\nTRY THROW CATCH FINAL NEXT LAST BREAK RETURN STOP\nCLEAR TO STEP AND OR NOT MOD DIV END\n\nThe variable values may be of virtually any Perl type, including simple scalars, references to\nlists, hash arrays, subroutines or objects. The Template Toolkit will automatically apply the\ncorrect procedure to accessing these values as they are used in the template.\n\nExample data:\n\nmy $vars = {\narticle => 'The Third Shoe',\nperson  => {\nid    => 314,\nname  => 'Mr. Blue',\nemail => 'blue@nowhere.org',\n},\nprimes  => [ 2, 3, 5, 7, 11, 13 ],\nwizard  => sub { return join(' ', 'Abracadabra!', @) },\ncgi     => CGI->new('mode=submit&debug=1'),\n};\n\nExample template:\n\n[% article %]\n\n[% person.id %]: [% person.name %] <[% person.email %]>\n\n[% primes.first %] - [% primes.last %], including [% primes.3 %]\n[% primes.size %] prime numbers: [% primes.join(', ') %]\n\n[% wizard %]\n[% wizard('Hocus Pocus!') %]\n\n[% cgi.param('mode') %]\n\nGenerated output:\n\nThe Third Shoe\n\n314: Mr. Blue <blue@nowhere.org>\n\n2 - 13, including 7\n6 prime numbers: 2, 3, 5, 7, 11, 13\n\nAbracadabra!\nAbracadabra! Hocus Pocus!\n\nsubmit\n",
            "subsections": [
                {
                    "name": "Scalar Values",
                    "content": "Regular scalar variables are accessed by simply specifying their name. As these are just entries\nin the top-level variable hash they can be considered special cases of hash array referencing as\ndescribed below, with the main namespace hash automatically implied.\n\n[% article %]\n"
                },
                {
                    "name": "Hash Array References",
                    "content": "Members of hash arrays are accessed by specifying the hash reference and key separated by the\ndot '\".\"' operator.\n\nExample data:\n\nmy $vars = {\n'home' => 'http://www.myserver.com/homepage.html',\n'page' => {\n'this' => 'mypage.html',\n'next' => 'nextpage.html',\n'prev' => 'prevpage.html',\n},\n};\n\nExample template:\n\n<a href=\"[% home %]\">Home</a>\n<a href=\"[% page.prev %]\">Previous Page</a>\n<a href=\"[% page.next %]\">Next Page</a>\n\nGenerated output:\n\n<a href=\"http://www.myserver.com/homepage.html\">Home</a>\n<a href=\"prevpage.html\">Previous Page</a>\n<a href=\"nextpage.html\">Next Page</a>\n\nAny key in a hash which starts with a '\"\"' or '\".\"' character will be considered private and\ncannot be evaluated or updated from within a template. The undefined value will be returned for\nany such variable accessed which the Template Toolkit will silently ignore (unless the \"DEBUG\"\noption is enabled).\n\nExample data:\n\nmy $vars = {\nmessage => 'Hello World!',\nsecret => \"On the Internet, no-one knows you're a dog\",\nthing   => {\npublic    => 123,\nprivate  => 456,\n'.hidden' => 789,\n},\n};\n\nExample template:\n\n[% message %]           # outputs \"Hello World!\"\n[% secret %]           # no output\n[% thing.public %]      # outputs \"123\"\n[% thing.private %]    # no output\n[% thing..hidden %]     # ERROR: unexpected token (..)\n\nYou can disable this feature by setting the $Template::Stash::PRIVATE package variable to a\nfalse value.\n\n$Template::Stash::PRIVATE = undef;   # now you can thing.private\n\nTo access a hash entry using a key stored in another variable, prefix the key variable with\n'\"$\"' to have it interpolated before use (see \"Variable Interpolation\").\n\n[% pagename = 'next' %]\n[% page.$pagename %]       # same as [% page.next %]\n\nWhen you assign to a variable that contains multiple namespace elements (i.e. it has one or more\n'\".\"' characters in the name), any hashes required to represent intermediate namespaces will be\ncreated automatically. In this following example, the \"product\" variable automatically springs\ninto life as a hash array unless otherwise defined.\n\n[% product.id    = 'XYZ-2000'\nproduct.desc  = 'Bogon Generator'\nproduct.price = 666\n%]\n\nThe [% product.id %] [% product.desc %]\ncosts $[% product.price %].00\n\nGenerated output:\n\nThe XYZ-2000 Bogon Generator\ncosts $666.00\n\nYou can use Perl's familiar \"{\" ... \"}\" construct to explicitly create a hash and assign it to a\nvariable. Note that commas are optional between key/value pairs and \"=\" can be used in place of\n\"=>\".\n\n# minimal TT style\n[% product = {\nid    = 'XYZ-2000'\ndesc  = 'Bogon Generator'\nprice = 666\n}\n%]\n\n# perl style\n[% product = {\nid    => 'XYZ-2000',\ndesc  => 'Bogon Generator',\nprice => 666,\n}\n%]\n"
                },
                {
                    "name": "List References",
                    "content": "Items in lists are also accessed by use of the dot operator.\n\nExample data:\n\nmy $vars = {\npeople => [ 'Tom', 'Dick', 'Larry' ],\n};\n\nExample template:\n\n[% people.0 %]          # Tom\n[% people.1 %]          # Dick\n[% people.2 %]          # Larry\n\nThe \"FOREACH\" directive can be used to iterate through items in a list.\n\n[% FOREACH person IN people %]\nHello [% person %]\n[% END %]\n\nGenerated output:\n\nHello Tom\nHello Dick\nHello Larry\n\nLists can be constructed in-situ using the regular anonymous list \"[\" ... \"]\" construct. Commas\nbetween items are optional.\n\n[% cols = [ 'red', 'green', 'blue' ] %]\n\n[% FOREACH c IN cols %]\n[% c %]\n[% END %]\n\nor:\n\n[% FOREACH c IN [ 'red', 'green', 'blue' ] %]\n[% c %]\n[% END %]\n\nYou can also create simple numerical sequences using the \"..\" range operator:\n\n[% n = [ 1 .. 4 ] %]    # n is [ 1, 2, 3, 4 ]\n\n[% x = 4\ny = 8\nz = [x..y]           # z is [ 4, 5, 6, 7, 8 ]\n%]\n"
                },
                {
                    "name": "Subroutines",
                    "content": "Template variables can contain references to Perl subroutines. When the variable is used, the\nTemplate Toolkit will automatically call the subroutine, passing any additional arguments\nspecified. The return value from the subroutine is used as the variable value and inserted into\nthe document output.\n\nmy $vars = {\nwizard  => sub { return join(' ', 'Abracadabra!', @) },\n};\n\nExample template:\n\n[% wizard %]                    # Abracadabra!\n[% wizard('Hocus Pocus!') %]    # Abracadabra! Hocus Pocus!\n"
                },
                {
                    "name": "Objects",
                    "content": "Template variables can also contain references to Perl objects. Methods are called using the dot\noperator to specify the method against the object variable. Additional arguments can be\nspecified as with subroutines.\n\nuse CGI;\n\nmy $vars = {\n# hard coded CGI params for purpose of example\ncgi  => CGI->new('mode=submit&debug=1'),\n};\n\nExample template:\n\n[% FOREACH p IN cgi.param %]     # returns list of param keys\n[% p %] => [% cgi.param(p) %]   # fetch each param value\n[% END %]\n\nGenerated output:\n\nmode => submit\ndebug => 1\n\nObject methods can also be called as lvalues. That is, they can appear on the left side of an\nassignment. The method will be called passing the assigning value as an argument.\n\n[% myobj.method = 10 %]\n\nequivalent to:\n\n[% myobj.method(10) %]\n"
                },
                {
                    "name": "Passing Parameters and Returning Values",
                    "content": "Subroutines and methods will be passed any arguments specified in the template. Any template\nvariables in the argument list will first be evaluated and their resultant values passed to the\ncode.\n\nmy $vars = {\nmycode => sub { return 'received ' . join(', ', @) },\n};\n\ntemplate:\n\n[% foo = 10 %]\n[% mycode(foo, 20) %]       # received 10, 20\n\nNamed parameters may also be specified. These are automatically collected into a single hash\narray which is passed by reference as the last parameter to the sub-routine. Named parameters\ncan be specified using either \"=>\" or \"=\" and can appear anywhere in the argument list.\n\nmy $vars = {\nmyjoin => \\&myjoin,\n};\n\nsub myjoin {\n# look for hash ref as last argument\nmy $params = ref $[-1] eq 'HASH' ? pop : { };\nreturn join($params->{ joint } || ' + ', @);\n}\n\nExample template:\n\n[% myjoin(10, 20, 30) %]\n[% myjoin(10, 20, 30, joint = ' - ' %]\n[% myjoin(joint => ' * ', 10, 20, 30 %]\n\nGenerated output:\n\n10 + 20 + 30\n10 - 20 - 30\n10 * 20 * 30\n\nParenthesised parameters may be added to any element of a variable, not just those that are\nbound to code or object methods. At present, parameters will be ignored if the variable isn't\n\"callable\" but are supported for future extensions. Think of them as \"hints\" to that variable,\nrather than just arguments passed to a function.\n\n[% r = 'Romeo' %]\n[% r(100, 99, s, t, v) %]       # outputs \"Romeo\"\n\nUser code should return a value for the variable it represents. This can be any of the Perl data\ntypes described above: a scalar, or reference to a list, hash, subroutine or object. Where code\nreturns a list of multiple values the items will automatically be folded into a list reference\nwhich can be accessed as per normal.\n\nmy $vars = {\n# either is OK, first is recommended\nitems1 => sub { return [ 'foo', 'bar', 'baz' ] },\nitems2 => sub { return ( 'foo', 'bar', 'baz' ) },\n};\n\nExample template:\n\n[% FOREACH i IN items1 %]\n...\n[% END %]\n\n[% FOREACH i IN items2 %]\n...\n[% END %]\n"
                },
                {
                    "name": "Error Handling",
                    "content": "Errors can be reported from user code by calling \"die()\". Errors raised in this way are caught\nby the Template Toolkit and converted to structured exceptions which can be handled from within\nthe template. A reference to the exception object is then available as the \"error\" variable.\n\nmy $vars = {\nbarf => sub {\ndie \"a sick error has occurred\\n\";\n},\n};\n\nExample template:\n\n[% TRY %]\n[% barf %]       # calls sub which throws error via die()\n[% CATCH %]\n[% error.info %]     # outputs \"a sick error has occurred\\n\"\n[% END %]\n\nError messages thrown via \"die()\" are converted to exceptions of type \"undef\" (the literal\nstring \"undef\" rather than the undefined value). Exceptions of user-defined types can be thrown\nby calling \"die()\" with a reference to a Template::Exception object.\n\nuse Template::Exception;\n\nmy $vars = {\nlogin => sub {\n...do something...\ndie Template::Exception->new( badpwd => 'password too silly' );\n},\n};\n\nExample template:\n\n[% TRY %]\n[% login %]\n[% CATCH badpwd %]\nBad password: [% error.info %]\n[% CATCH %]\nSome other '[% error.type %]' error: [% error.info %]\n[% END %]\n\nThe exception types \"stop\" and \"return\" are used to implement the \"STOP\" and \"RETURN\"\ndirectives. Throwing an exception as:\n\ndie (Template::Exception->new('stop'));\n\nhas the same effect as the directive:\n\n[% STOP %]\n"
                }
            ]
        },
        "Virtual Methods": {
            "content": "The Template Toolkit implements a number of \"virtual methods\" which can be applied to scalars,\nhashes or lists. For example:\n\n[% mylist = [ 'foo', 'bar', 'baz' ] %]\n[% newlist = mylist.sort %]\n\nHere \"mylist\" is a regular reference to a list, and 'sort' is a virtual method that returns a\nnew list of the items in sorted order. You can chain multiple virtual methods together. For\nexample:\n\n[% mylist.sort.join(', ') %]\n\nHere the \"join\" virtual method is called to join the sorted list into a single string,\ngenerating the following output:\n\nbar, baz, foo\n\nSee Template::Manual::VMethods for details of all the virtual methods available.\n",
            "subsections": []
        },
        "Variable Interpolation": {
            "content": "The Template Toolkit uses \"$\" consistently to indicate that a variable should be interpolated in\nposition. Most frequently, you see this in double-quoted strings:\n\n[% fullname = \"$honorific $firstname $surname\" %]\n\nOr embedded in plain text when the \"INTERPOLATE\" option is set:\n\nDear $honorific $firstname $surname,\n\nThe same rules apply within directives. If a variable is prefixed with a \"$\" then it is replaced\nwith its value before being used. The most common use is to retrieve an element from a hash\nwhere the key is stored in a variable.\n\n[% uid = 'abw' %]\n[% users.$uid %]         # same as 'userlist.abw'\n\nCurly braces can be used to delimit interpolated variable names where necessary.\n\n[% users.${me.id}.name %]\n\nDirectives such as \"INCLUDE\", \"PROCESS\", etc., that accept a template name as the first\nargument, will automatically quote it for convenience.\n\n[% INCLUDE foo/bar.txt %]\n\nThe above example is equivalent to:\n\n[% INCLUDE \"foo/bar.txt\" %]\n\nTo \"INCLUDE\" a template whose name is stored in a variable, simply prefix the variable name with\n\"$\" to have it interpolated.\n\n[% myfile = 'header' %]\n[% INCLUDE $myfile %]\n\nThis is equivalent to:\n\n[% INCLUDE header %]\n\nNote also that a variable containing a reference to a Template::Document object can also be\nprocessed in this way.\n\nmy $vars = {\nheader => Template::Document->new({ ... }),\n};\n\nExample template:\n\n[% INCLUDE $header %]\n",
            "subsections": []
        },
        "Local and Global Variables": {
            "content": "Any simple variables that you create, or any changes you make to existing variables, will only\npersist while the template is being processed. The top-level variable hash is copied before\nprocessing begins and any changes to variables are made in this copy, leaving the original\nintact.\n\nThe same thing happens when you \"INCLUDE\" another template. The current namespace hash is cloned\nto prevent any variable changes made in the included template from interfering with existing\nvariables. The \"PROCESS\" option bypasses the localisation step altogether making it slightly\nfaster, but requiring greater attention to the possibility of side effects caused by creating or\nchanging any variables within the processed template.\n\n[% BLOCK changename %]\n[% name = 'bar' %]\n[% END %]\n\n[% name = 'foo' %]\n[% INCLUDE changename %]\n[% name %]              # foo\n[% PROCESS changename %]\n[% name %]              # bar\n\nDotted compound variables behave slightly differently because the localisation process is only\nskin deep. The current variable namespace hash is copied, but no attempt is made to perform a\ndeep-copy of other structures within it (hashes, arrays, objects, etc). A variable referencing a\nhash, for example, will be copied to create a new reference but which points to the same hash.\nThus, the general rule is that simple variables (undotted variables) are localised, but existing\ncomplex structures (dotted variables) are not.\n\n[% BLOCK allchange %]\n[% x = 20 %]         # changes copy\n[% y.z = 'zulu' %]       # changes original\n[% END %]\n\n[% x = 10\ny = { z => 'zebra' }\n%]\n[% INCLUDE allchange %]\n[% x %]             # still '10'\n[% y.z %]               # now 'zulu'\n\nIf you create a complex structure such as a hash or list reference within a local template\ncontext then it will cease to exist when the template is finished processing.\n\n[% BLOCK newstuff %]\n[% # define a new 'y' hash array in local context\ny = { z => 'zulu' }\n%]\n[% END %]\n\n[% x = 10 %]\n[% INCLUDE newstuff %]\n[% x %]             # outputs '10'\n[% y %]             # nothing, y is undefined\n\nSimilarly, if you update an element of a compound variable which *doesn't* already exists then a\nhash will be created automatically and deleted again at the end of the block.\n\n[% BLOCK newstuff %]\n[% y.z = 'zulu' %]\n[% END %]\n\nHowever, if the hash *does* already exist then you will modify the original with permanent\neffect. To avoid potential confusion, it is recommended that you don't update elements of\ncomplex variables from within blocks or templates included by another.\n\nIf you want to create or update truly global variables then you can use the 'global' namespace.\nThis is a hash array automatically created in the top-level namespace which all templates,\nlocalised or otherwise see the same reference to. Changes made to variables within this hash are\nvisible across all templates.\n\n[% global.version = 123 %]\n",
            "subsections": []
        },
        "Compile Time Constant Folding": {
            "content": "In addition to variables that get resolved each time a template is processed, you can also\ndefine variables that get resolved just once when the template is compiled. This generally\nresults in templates processing faster because there is less work to be done.\n\nTo define compile-time constants, specify a \"CONSTANTS\" hash as a constructor item as per\n\"VARIABLES\". The \"CONSTANTS\" hash can contain any kind of complex, nested, or dynamic data\nstructures, just like regular variables.\n\nmy $tt = Template->new({\nCONSTANTS => {\nversion => 3.14,\nrelease => 'skyrocket',\ncol     => {\nback => '#ffffff',\nfore => '#000000',\n},\nmyobj => My::Object->new(),\nmysub => sub { ... },\njoint => ', ',\n},\n});\n\nWithin a template, you access these variables using the \"constants\" namespace prefix.\n\nVersion [% constants.version %] ([% constants.release %])\nBackground: [% constants.col.back %]\n\nWhen the template is compiled, these variable references are replaced with the corresponding\nvalue. No further variable lookup is then required when the template is processed.\n\nYou can call subroutines, object methods, and even virtual methods on constant variables.\n\n[% constants.mysub(10, 20) %]\n[% constants.myobj(30, 40) %]\n[% constants.col.keys.sort.join(', ') %]\n\nOne important proviso is that any arguments you pass to subroutines or methods must also be\nliteral values or compile time constants.\n\nFor example, these are both fine:\n\n# literal argument\n[% constants.col.keys.sort.join(', ') %]\n\n# constant argument\n[% constants.col.keys.sort.join(constants.joint) %]\n\nBut this next example will raise an error at parse time because \"joint\" is a runtime variable\nand cannot be determined at compile time.\n\n# ERROR: runtime variable argument!\n[% constants.col.keys.sort.join(joint) %]\n\nThe \"CONSTANTSNAMESPACE\" option can be used to provide a different namespace prefix for\nconstant variables. For example:\n\nmy $tt = Template->new({\nCONSTANTS => {\nversion => 3.14,\n# ...etc...\n},\nCONSTANTSNAMESPACE => 'const',\n});\n\nConstants would then be referenced in templates as:\n\n[% const.version %]\n",
            "subsections": []
        },
        "Special Variables": {
            "content": "A number of special variables are automatically defined by the Template Toolkit.\n\ntemplate\nThe \"template\" variable contains a reference to the main template being processed, in the form\nof a Template::Document object. This variable is correctly defined within \"PREPROCESS\",\n\"PROCESS\" and \"POSTPROCESS\" templates, allowing standard headers, footers, etc., to access\nmetadata items from the main template. The \"name\" and \"modtime\" metadata items are automatically\nprovided, giving the template name and modification time in seconds since the epoch.\n\nNote that the \"template\" variable always references the top-level template, even when processing\nother template components via \"INCLUDE\", \"PROCESS\", etc.\n\ncomponent\nThe \"component\" variable is like \"template\" but always contains a reference to the current,\ninnermost template component being processed. In the main template, the \"template\" and\n\"component\" variable will reference the same Template::Document object. In any other template\ncomponent called from the main template, the \"template\" variable will remain unchanged, but\n\"component\" will contain a new reference to the current component.\n\nThis example should demonstrate the difference:\n\n$template->process('foo')\n|| die $template->error(), \"\\n\";\n\nfoo template:\n\n[% template.name %]         # foo\n[% component.name %]        # foo\n[% PROCESS footer %]\n\nfooter template:\n\n[% template.name %]         # foo\n[% component.name %]        # footer\n\nAdditionally, the \"component\" variable has two special fields: \"caller\" and \"callers\". \"caller\"\ncontains the name of the template that called the current template (or undef if the values of\n\"template\" and \"component\" are the same). \"callers\" contains a reference to a list of all the\ntemplates that have been called on the road to calling the current component template (like a\ncall stack), with the outer-most template first.\n\nHere's an example:\n\nouter.tt2 template:\n\n[% component.name %]        # 'outer.tt2'\n[% component.caller %]      # undef\n[% component.callers %]     # undef\n[% PROCESS 'middle.tt2' %]\n\nmiddle.tt2 template:\n\n[% component.name %]        # 'middle.tt2'\n[% component.caller %]      # 'outer.tt2'\n[% component.callers %]     # [ 'outer.tt2' ]\n[% PROCESS 'inner.tt2' %]\n\ninner.tt2 template:\n\n[% component.name %]        # 'inner.tt2'\n[% component.caller %]      # 'middle.tt2'\n[% component.callers %]     # [ 'outer.tt2', 'middle.tt2' ]\n\nloop\nWithin a \"FOREACH\" loop, the \"loop\" variable references the Template::Iterator object\nresponsible for controlling the loop.\n\n[% FOREACH item = [ 'foo', 'bar', 'baz' ] -%]\n[% \"Items:\\n\" IF loop.first -%]\n[% loop.count %]/[% loop.size %]: [% item %]\n[% END %]\n\nerror\nWithin a \"CATCH\" block, the \"error\" variable contains a reference to the Template::Exception\nobject thrown from within the \"TRY\" block. The \"type\" and \"info\" methods can be called or the\nvariable itself can be printed for automatic stringification into a message of the form \"\"$type\nerror - $info\"\". See Template::Exception for further details.\n\n[% TRY %]\n...\n[% CATCH %]\n[% error %]\n[% END %]\n\ncontent\nThe \"WRAPPER\" method captures the output from a template block and then includes a named\ntemplate, passing the captured output as the 'content' variable.\n\n[% WRAPPER box %]\nBe not afeard; the isle is full of noises,\nSounds and sweet airs, that give delight and hurt not.\n[% END %]\n\n[% BLOCK box %]\n<blockquote class=\"prose\">\n[% content %]\n</blockquote>\n[% END %]\n",
            "subsections": []
        },
        "Compound Variables": {
            "content": "Compound 'dotted' variables may contain any number of separate elements. Each element may\nevaluate to any of the permitted variable types and the processor will then correctly use this\nvalue to evaluate the rest of the variable. Arguments may be passed to any of the intermediate\nelements.\n\n[% myorg.people.sort('surname').first.fullname %]\n\nIntermediate variables may be used and will behave entirely as expected.\n\n[% sorted = myorg.people.sort('surname') %]\n[% sorted.first.fullname %]\n\nThis simplified dotted notation has the benefit of hiding the implementation details of your\ndata. For example, you could implement a data structure as a hash array one day and then change\nit to an object the next without requiring any change to the templates.\n",
            "subsections": []
        }
    },
    "summary": "Template::Manual::Variables - Template variables and code bindings",
    "flags": [],
    "examples": [],
    "see_also": []
}