{
    "mode": "perldoc",
    "parameter": "Template::Tutorial::Web",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Template%3A%3ATutorial%3A%3AWeb/json",
    "generated": "2026-06-11T23:58:25Z",
    "sections": {
        "NAME": {
            "content": "Template::Tutorial::Web - Generating Web Content Using the Template Toolkit\n",
            "subsections": []
        },
        "Overview": {
            "content": "This tutorial document provides a introduction to the Template Toolkit and demonstrates some of\nthe typical ways it may be used for generating web content. It covers the generation of static\npages from templates using the tpage and ttree scripts and then goes on to show dynamic content\ngeneration using CGI scripts and Apache/modperl handlers.\n\nVarious features of the Template Toolkit are introduced and described briefly and explained by\nuse of example. For further information, see Template, Template::Manual and the various sections\nwithin it. e.g\n\nperldoc Template                    # Template.pm module usage\nperldoc Template::Manual            # index to manual\nperldoc Template::Manual::Config    # e.g. configuration options\n\nThe documentation is also available in HTML format to read online, or download from the Template\nToolkit web site:\n\nhttp://template-toolkit.org/docs/\n",
            "subsections": []
        },
        "Introduction": {
            "content": "The Template Toolkit is a set of Perl modules which collectively implement a template processing\nsystem.\n\nA template is a text document with special markup tags embedded in it. By default, the Template\nToolkit uses '\"[%\"' and '\"%]\"' to denote the start and end of a tag. Here's an example:\n\n[% INCLUDE header %]\n\nPeople of [% planet %], your attention please.\n\nThis is [% captain %] of the\nGalactic Hyperspace Planning Council.\n\nAs you will no doubt be aware, the plans\nfor development of the outlying regions\nof the Galaxy require the building of a\nhyperspatial express route through your\nstar system, and regrettably your planet\nis one of those scheduled for destruction.\n\nThe process will take slightly less than\n[% time %].\n\nThank you.\n\n[% INCLUDE footer %]\n\nTags can contain simple *variables* (like \"planet\" and \"captain\") and more complex *directives*\nthat start with an upper case keyword (like \"INCLUDE\"). A directive is an instruction that tells\nthe template processor to perform some action, like processing another template (\"header\" and\n\"footer\" in this example) and inserting the output into the current template. In fact, the\nsimple variables we mentioned are actually \"GET\" directives, but the \"GET\" keyword is optional.\n\nPeople of [% planet %], your attention please.      # short form\nPeople of [% GET planet %], your attention please.  # long form\n\nOther directives include \"SET\" to set a variable value (the \"SET\" keyword is also optional),\n\"FOREACH\" to iterate through a list of values, and \"IF\", \"UNLESS\", \"ELSIF\" and \"ELSE\" to declare\nconditional blocks.\n\nThe Template Toolkit processes all *text* files equally, regardless of what kind of content they\ncontain. So you can use TT to generate HTML, XML, CSS, Javascript, Perl, RTF, LaTeX, or any\nother text-based format. In this tutorial, however, we'll be concentrating on generating HTML\nfor web pages.\n",
            "subsections": []
        },
        "Generating Static Web Content": {
            "content": "Here's an example of a template used to generate an HTML document.\n\n[%  INCLUDE header\ntitle = 'This is an HTML example';\n\npages = [\n{ url   = 'http://foo.org'\ntitle = 'The Foo Organisation'\n}\n{ url   = 'http://bar.org'\ntitle = 'The Bar Organisation'\n}\n]\n%]\n<h1>Some Interesting Links</h1>\n<ul>\n[%  FOREACH page IN pages %]\n<li><a href=\"[% page.url %]\">[% page.title %]</a>\n[%  END %]\n</ul>\n\n[% INCLUDE footer %]\n\nThis example shows how the \"INCLUDE\" directive is used to load and process separate '\"header\"'\nand '\"footer\"' template files, including the output in the current document. These files might\nlook something like this:\n\nheader:\n\n<html>\n<head>\n<title>[% title %]</title>\n</head>\n<body>\n\nfooter:\n\n<div class=\"copyright\">\n&copy; Copyright 2007 Arthur Dent\n</div>\n</body>\n</html>\n\nThe example also uses the \"FOREACH\" directive to iterate through the '\"pages\"' list to build a\ntable of links. In this example, we have defined this list within the template to contain a\nnumber of hash references, each containing a '\"url\"' and '\"title\"' member. The \"FOREACH\"\ndirective iterates through the list, aliasing '\"page\"' to each item (in this case, hash array\nreferences). The \"[% page.url %]\" and \"[% page.title %]\" directives then access the individual\nvalues in the hash arrays and insert them into the document.\n",
            "subsections": [
                {
                    "name": "Using tpage",
                    "content": "Having created a template file we can now process it to generate some real output. The quickest\nand easiest way to do this is to use the tpage script. This is provided as part of the Template\nToolkit and should be installed in your usual Perl bin directory.\n\nAssuming you saved your template file as example.html, you would run the command:\n\n$ tpage example.html\n\nThis will process the template file, sending the output to \"STDOUT\" (i.e. whizzing past you on\nthe screen). You may want to redirect the output to a file but be careful not to specify the\nsame name as the template file, or you'll overwrite it. You may want to use one prefix for your\ntemplates (e.g. '\".tt\"') and another (e.g. '\".html\"') for the output files.\n\n$ tpage example.tt > example.html\n\nOr you can redirect the output to another directory. e.g.\n\n$ tpage templates/example.tt > html/example.html\n\nThe output generated would look like this:\n\n<html>\n<head>\n<title>This is an HTML example</title>\n</head>\n<body>\n<h1>Some Interesting Links</h1>\n<ul>\n<li><a href=\"http://foo.org\">The Foo Organsiation</a>\n<li><a href=\"http://bar.org\">The Bar Organsiation</a>\n</ul>\n<div class=\"copyright\">\n&copy; Copyright 2007 Arthur Dent\n</div>\n</body>\n</html>\n\nThe header and footer template files have been included (assuming you created them and they're\nin the current directory) and the link data has been built into an HTML list.\n"
                },
                {
                    "name": "Using ttree",
                    "content": "The tpage script gives you a simple and easy way to process a single template without having to\nwrite any Perl code. The <ttree:Template::Tools::ttree> script, also distributed as part of the\nTemplate Toolkit, provides a more flexible way to process a number of template documents in one\ngo.\n\nThe first time you run the script, it will ask you if it should create a configuration file\n(.ttreerc) in your home directory. Answer \"y\" to have it create the file.\n\nThe <ttree:Template::Tools::ttree> documentation describes how you can change the location of\nthis file and also explains the syntax and meaning of the various options in the file. Comments\nare written to the sample configuration file which should also help.\n\nIn brief, the configuration file describes the directories in which template files are to be\nfound (\"src\"), where the corresponding output should be written to (\"dest\"), and any other\ndirectories (\"lib\") that may contain template files that you plan to \"INCLUDE\" into your source\ndocuments. You can also specify processing options (such as \"verbose\" and \"recurse\") and provide\nregular expression to match files that you don't want to process (\"ignore\", \"accept\")> or should\nbe copied instead of being processed as templates (\"copy\").\n\nAn example .ttreerc file is shown here:\n\n$HOME/.ttreerc:\n\nverbose\nrecurse\n\n# this is where I keep other ttree config files\ncfg = ~/.ttree\n\nsrc  = ~/websrc/src\nlib  = ~/websrc/lib\ndest = ~/publichtml/test\n\nignore = \\b(CVS|RCS)\\b\nignore = ^#\n\nYou can create many different configuration files and store them in the directory specified in\nthe \"cfg\" option, shown above. You then add the \"-f filename\" option to \"ttree\" to have it read\nthat file.\n\nWhen you run the script, it compares all the files in the \"src\" directory (including those in\nsub-directories if the \"recurse\" option is set), with those in the \"dest\" directory. If the\ndestination file doesn't exist or has an earlier modification time than the corresponding source\nfile, then the source will be processed with the output written to the destination file. The\n\"-a\" option forces all files to be processed, regardless of modification times.\n\nThe script *doesn't* process any of the files in the \"lib\" directory, but it does add it to the\n\"INCLUDEPATH\" for the template processor so that it can locate these files via an \"INCLUDE\",\n\"PROCESS\" or \"WRAPPER\" directive. Thus, the \"lib\" directory is an excellent place to keep\ntemplate elements such as header, footers, etc., that aren't complete documents in their own\nright.\n\nYou can also specify various Template Toolkit options from the configuration file. Consult the\nttree documentation and help summary (\"ttree -h\") for full details. e.g.\n\n$HOME/.ttreerc:\n\npreprocess = config\ninterpolate\npostchomp\n\nThe \"preprocess\" option allows you to specify a template file which should be processed before\neach file. Unsurprisingly, there's also a \"postprocess\" option to add a template after each\nfile. In the fragment above, we have specified that the \"config\" template should be used as a\nprefix template. We can create this file in the \"lib\" directory and use it to define some common\nvariables, including those web page links we defined earlier and might want to re-use in other\ntemplates. We could also include an HTML header, title, or menu bar in this file which would\nthen be prepended to each and every template file, but for now we'll keep all that in a separate\n\"header\" file.\n\n$lib/config:\n\n[% root     = '~/abw'\nhome     = \"$root/index.html\"\nimages   = \"$root/images\"\nemail    = 'abw@wardley.org'\ngraphics = 1\nwebpages = [\n{ url => 'http://foo.org', title => 'The Foo Organsiation' }\n{ url => 'http://bar.org', title => 'The Bar Organsiation' }\n]\n%]\n\nAssuming you've created or copied the \"header\" and \"footer\" files from the earlier example into\nyour \"lib\" directory, you can now start to create web pages like the following in your \"src\"\ndirectory and process them with \"ttree\".\n\n$src/newpage.html:\n\n[% INCLUDE header\ntitle = 'Another Template Toolkit Test Page'\n%]\n\n<a href=\"[% home %]\">Home</a>\n<a href=\"mailto:[% email %]\">Email</a>\n\n[% IF graphics %]\n<img src=\"[% images %]/logo.gif\" align=right width=60 height=40>\n[% END %]\n\n[% INCLUDE footer %]\n\nHere we've shown how pre-defined variables can be used as flags to enable certain feature (e.g.\n\"graphics\") and to specify common items such as an email address and URL's for the home page,\nimages directory and so on. This approach allows you to define these values once so that they're\nconsistent across all pages and can easily be changed to new values.\n\nWhen you run ttree, you should see output similar to the following (assuming you have the\nverbose flag set).\n\nttree 2.9 (Template Toolkit version 2.20)\n\nSource: /home/abw/websrc/src\nDestination: /home/abw/publichtml/test\nInclude Path: [ /home/abw/websrc/lib ]\nIgnore: [ \\b(CVS|RCS)\\b, ^# ]\nCopy: [  ]\nAccept: [ * ]\n\n+ newpage.html\n\nThe \"+\" in front of the \"newpage.html\" filename shows that the file was processed, with the\noutput being written to the destination directory. If you run the same command again, you'll see\nthe following line displayed instead showing a \"-\" and giving a reason why the file wasn't\nprocessed.\n\n- newpage.html                     (not modified)\n\nIt has detected a \"newpage.html\" in the destination directory which is more recent than that in\nthe source directory and so hasn't bothered to waste time re-processing it. To force all files\nto be processed, use the \"-a\" option. You can also specify one or more filenames as command line\narguments to \"ttree\":\n\ntpage newpage.html\n\nThis is what the destination page looks like.\n\n$dest/newpage.html:\n\n<html>\n<head>\n<title>Another Template Toolkit Test Page</title>\n</head>\n<body>\n\n<a href=\"~/abw/index.html\">Home</a>\n<a href=\"mailto:abw@wardley.org\">Email me</a>\n<img src=\"~/abw/images/logo.gif\" align=right width=60 height=40>\n\n<div class=\"copyright\">\n&copy; Copyright 2007 Arthur Dent\n</div>\n</body>\n</html>\n\nYou can add as many documents as you like to the \"src\" directory and \"ttree\" will apply the same\nprocess to them all. In this way, it is possible to build an entire tree of static content for a\nweb site with a single command. The added benefit is that you can be assured of consistency in\nlinks, header style, or whatever else you choose to implement in terms of common templates\nelements or variables.\n"
                }
            ]
        },
        "Dynamic Content Generation Via CGI Script": {
            "content": "The Template module provides a simple front-end to the Template Toolkit for use in CGI scripts\nand Apache/modperl handlers. Simply \"use\" the Template module, create an object instance with\nthe new() method and then call the process() method on the object, passing the name of the\ntemplate file as a parameter. The second parameter passed is a reference to a hash array of\nvariables that we want made available to the template:\n\n#!/usr/bin/perl\nuse strict;\nuse warnings;\nuse Template;\n\nmy $file = 'src/greeting.html';\nmy $vars = {\nmessage  => \"Hello World\\n\"\n};\n\nmy $template = Template->new();\n\n$template->process($file, $vars)\n|| die \"Template process failed: \", $template->error(), \"\\n\";\n\nSo that our scripts will work with the same template files as our earlier examples, we'll can\nadd some configuration options to the constructor to tell it about our environment:\n\nmy $template->new({\n# where to find template files\nINCLUDEPATH => ['/home/abw/websrc/src', '/home/abw/websrc/lib'],\n# pre-process lib/config to define any extra values\nPREPROCESS  => 'config',\n});\n\nNote that here we specify the \"config\" file as a \"PREPROCESS\" option. This means that the\ntemplates we process can use the same global variables defined earlier for our static pages. We\ndon't have to replicate their definitions in this script. However, we can supply additional data\nand functionality specific to this script via the hash of variables that we pass to the\n\"process()\" method.\n\nThese entries in this hash may contain simple text or other values, references to lists, others\nhashes, sub-routines or objects. The Template Toolkit will automatically apply the correct\nprocedure to access these different types when you use the variables in a template.\n\nHere's a more detailed example to look over. Amongst the different template variables we define\nin $vars, we create a reference to a CGI object and a \"getuserprojects()\" sub-routine.\n\n#!/usr/bin/perl\nuse strict;\nuse warnings;\nuse Template;\nuse CGI;\n\n$| = 1;\nprint \"Content-type: text/html\\n\\n\";\n\nmy $file = 'userinfo.html';\nmy $vars = {\n'version'  => 3.14,\n'days'     => [ qw( mon tue wed thu fri sat sun ) ],\n'worklist' => \\&getuserprojects,\n'cgi'      => CGI->new(),\n'me'       => {\n'id'     => 'abw',\n'name'   => 'Andy Wardley',\n},\n};\n\nsub getuserprojects {\nmy $user = shift;\nmy @projects = ...   # do something to retrieve data\nreturn \\@projects;\n}\n\nmy $template = Template->new({\nINCLUDEPATH => '/home/abw/websrc/src:/home/abw/websrc/lib',\nPREPROCESS  => 'config',\n});\n\n$template->process($file, $vars)\n|| die $template->error();\n\nHere's a sample template file that we might create to build the output for this script.\n\n$src/userinfo.html:\n\n[% INCLUDE header\ntitle = 'Template Toolkit CGI Test'\n%]\n\n<a href=\"mailto:[% email %]\">Email [% me.name %]</a>\n\n<p>This is version [% version %]</p>\n\n<h3>Projects</h3>\n<ul>\n[% FOREACH project IN worklist(me.id) %]\n<li> <a href=\"[% project.url %]\">[% project.name %]</a>\n[% END %]\n</ul>\n\n[% INCLUDE footer %]\n\nThis example shows how we've separated the Perl implementation (code) from the presentation\n(HTML). This not only makes them easier to maintain in isolation, but also allows the re-use of\nexisting template elements such as headers and footers, etc. By using template to create the\noutput of your CGI scripts, you can give them the same consistency as your static pages built\nvia ttree or other means.\n\nFurthermore, we can modify our script so that it processes any one of a number of different\ntemplates based on some condition. A CGI script to maintain a user database, for example, might\nprocess one template to provide an empty form for new users, the same form with some default\nvalues set for updating an existing user record, a third template for listing all users in the\nsystem, and so on. You can use any Perl functionality you care to write to implement the logic\nof your application and then choose one or other template to generate the desired output for the\napplication state.\n",
            "subsections": []
        },
        "Dynamic Content Generation Via Apache/ModPerl Handler": {
            "content": "NOTE: the Apache::Template module is available from CPAN and provides a simple and easy to use\nApache/modperl interface to the Template Toolkit. Although basic, it implements most, if not\nall of what is described below, and it avoids the need to write your own handler. However, in\nmany cases, you'll want to write your own handler to customise processing for your own need, and\nthis section will show you how to get started.\n\nThe Template module can be used from an Apache/modperl handler. Here's an example of a typical\nApache httpd.conf file:\n\nPerlModule CGI;\nPerlModule Template\nPerlModule MyOrg::Apache::User\n\nPerlSetVar websrcroot   /home/abw/websrc\n\n<Location /user/bin>\nSetHandler     perl-script\nPerlHandler    MyOrg::Apache::User\n</Location>\n\nThis defines a location called \"/user/bin\" to which all requests will be forwarded to the\n\"handler()\" method of the \"MyOrg::Apache::User\" module. That module might look something like\nthis:\n\npackage MyOrg::Apache::User;\n\nuse strict;\nuse vars qw( $VERSION );\nuse Apache::Constants qw( :common );\nuse Template qw( :template );\nuse CGI;\n\n$VERSION = 1.59;\n\nsub handler {\nmy $r = shift;\n\nmy $websrc = $r->dirconfig('websrcroot')\nor return fail($r, SERVERERROR,\n\"'websrcroot' not specified\");\n\nmy $template = Template->new({\nINCLUDEPATH  => \"$websrc/src/user:$websrc/lib\",\nPREPROCESS   => 'config',\nOUTPUT        => $r,     # direct output to Apache request\n});\n\nmy $params = {\nuri     => $r->uri,\ncgi     => CGI->new,\n};\n\n# use the pathinfo to determine which template file to process\nmy $file = $r->pathinfo;\n$file =~ s[^/][];\n\n$r->contenttype('text/html');\n$r->sendhttpheader;\n\n$template->process($file, $params)\n|| return fail($r, SERVERERROR, $template->error());\n\nreturn OK;\n}\n\nsub fail {\nmy ($r, $status, $message) = @;\n$r->logreason($message, $r->filename);\nreturn $status;\n}\n\nThe handler accepts the request and uses it to determine the \"websrcroot\" value from the config\nfile. This is then used to define an \"INCLUDEPATH\" for a new Template object. The URI is\nextracted from the request and a CGI object is created. These are both defined as template\nvariables.\n\nThe name of the template file itself is taken from the \"PATHINFO\" element of the request. In\nthis case, it would comprise the part of the URL coming after \"/user/bin\", e.g for\n\"/user/bin/edit\", the template file would be \"edit\" located in \"$websrc/src/user\". The headers\nare sent and the template file is processed. All output is sent directly to the \"print()\" method\nof the Apache request object.\n",
            "subsections": []
        },
        "Using Plugins to Extend Functionality": {
            "content": "As we've already shown, it is possible to bind Perl data and functions to template variables\nwhen creating dynamic content via a CGI script or Apache/modperl process. The Template Toolkit\nalso supports a plugin interface which allows you define such additional data and/or\nfunctionality in a separate module and then load and use it as required with the \"USE\"\ndirective.\n\nThe main benefit to this approach is that you can load the extension into any template document,\neven those that are processed \"statically\" by \"tpage\" or \"ttree\". You *don't* need to write a\nPerl wrapper to explicitly load the module and make it available via the stash.\n\nLet's demonstrate this principle using the \"DBI\" plugin written by Simon Matthews (available\nfrom CPAN). You can create this template in your \"src\" directory and process it using \"ttree\" to\nsee the results. Of course, this example relies on the existence of the appropriate SQL database\nbut you should be able to adapt it to your own resources, or at least use it as a demonstrative\nexample of what's possible.\n\n[% INCLUDE header\ntitle = 'User Info'\n%]\n\n[% USE DBI('dbi:mSQL:mydbname') %]\n\n<table border=0 width=\"100%\">\n<tr>\n<th>User ID</th>\n<th>Name</th>\n<th>Email</th>\n</tr>\n[% FOREACH user IN DBI.query('SELECT * FROM user ORDER BY id') %]\n<tr>\n<td>[% user.id %]</td>\n<td>[% user.name %]</td>\n<td>[% user.email %]</td>\n</tr>\n[% END %]\n</table>\n\n[% INCLUDE footer %]\n\nA plugin is simply a Perl module in a known location and conforming to a known standard such\nthat the Template Toolkit can find and load it automatically. You can create your own plugin by\ninheriting from the Template::Plugin module.\n\nHere's an example which defines some data items (\"foo\" and \"people\") and also an object method\n(\"bar\"). We'll call the plugin \"FooBar\" for want of a better name and create it in the\n\"MyOrg::Template::Plugin::FooBar\" package. We've added a \"MyOrg\" to the regular\n\"Template::Plugin::*\" package to avoid any conflict with existing plugins.\n\npackage MyOrg::Template::Plugin::FooBar;\nuse base 'Template::Plugin'\nour $VERSION = 1.23;\n\nsub new {\nmy ($class, $context, @params) = @;\n\nbless {\nCONTEXT => $context,\nfoo      => 25,\npeople   => [ 'tom', 'dick', 'harry' ],\n}, $class;\n}\n\nsub bar {\nmy ($self, @params) = @;\n# ...do something...\nreturn $somevalue;\n}\n\nThe plugin constructor \"new()\" receives the class name as the first parameter, as is usual in\nPerl, followed by a reference to something called a Template::Context object. You don't need to\nworry too much about this at the moment, other than to know that it's the main processing object\nfor the Template Toolkit. It provides access to the functionality of the processor and some\nplugins may need to communicate with it. We don't at this stage, but we'll save the reference\nanyway in the \"CONTEXT\" member. The leading underscore is a convention which indicates that\nthis item is private and the Template Toolkit won't attempt to access this member. The other\nmembers defined, \"foo\" and \"people\" are regular data items which will be made available to\ntemplates using this plugin. Following the context reference are passed any additional\nparameters specified with the USE directive, such as the data source parameter,\n\"dbi:mSQL:mydbname\", that we used in the earlier DBI example.\n\nIf you don't or can't install it to the regular place for your Perl modules (perhaps because you\ndon't have the required privileges) then you can set the PERL5LIB environment variable to\nspecify another location. If you're using \"ttree\" then you can add the following line to your\nconfiguration file instead.\n\n$HOME/.ttreerc:\n\nperl5lib = /path/to/modules\n\nOne further configuration item must be added to inform the toolkit of the new package name we\nhave adopted for our plugins:\n\n$HOME/.ttreerc:\n\npluginbase = 'MyOrg::Template::Plugin'\n\nIf you're writing Perl code to control the Template modules directly, then this value can be\npassed as a configuration parameter when you create the module.\n\nuse Template;\n\nmy $template = Template->new({\nPLUGINBASE => 'MyOrg::Template::Plugin'\n});\n\nNow we can create a template which uses this plugin:\n\n[% INCLUDE header\ntitle = 'FooBar Plugin Test'\n%]\n\n[% USE FooBar %]\n\nSome values available from this plugin:\n[% FooBar.foo %] [% FooBar.bar %]\n\nThe users defined in the 'people' list:\n[% FOREACH uid = FooBar.people %]\n* [% uid %]\n[% END %]\n\n[% INCLUDE footer %]\n\nThe \"foo\", \"bar\", and \"people\" items of the FooBar plugin are automatically resolved to the\nappropriate data items or method calls on the underlying object.\n\nUsing this approach, it is possible to create application functionality in a single module which\ncan then be loaded and used on demand in any template. The simple interface between template\ndirectives and plugin objects allows complex, dynamic content to be built from a few simple\ntemplate documents without knowing anything about the underlying implementation.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Andy Wardley <abw@wardley.org> <http://wardley.org/>\n",
            "subsections": []
        },
        "COPYRIGHT": {
            "content": "Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.\n\nThis module is free software; you can redistribute it and/or modify it under the same terms as\nPerl itself.\n",
            "subsections": []
        }
    },
    "summary": "Template::Tutorial::Web - Generating Web Content Using the Template Toolkit",
    "flags": [],
    "examples": [],
    "see_also": []
}