This module attempts to make using HTML templates simple and natural. It extends standard HTML with a few new HTML-esque tags - <TMPL_VAR>, <TMPL_LOOP>, <TMPL_INCLUDE>, <TMPL_IF>, <TMPL_ELSE> and <TMPL_UNLESS>. The file written with HTML and these new tags is called a template. It is usually saved separate from your script - possibly even created by someone else! Using this module you fill in the values for the variables, loops and branches declared in the template. This allows you to separate design - the HTML - from the data, which you generate in the Perl script.

It is true that there are a number of packages out there to do HTML templates. On the one hand you have things like HTML::Embperl which allows you freely mix Perl with HTML. On the other hand lie home-grown variable substitution solutions. Hopefully the module can find a place between the two.

One advantage of this module over a full HTML::Embperl-esque solution is that it enforces an important divide - design and programming. By limiting the programmer to just using simple variables and loops in the HTML, the template remains accessible to designers and other non-perl people. The use of HTML-esque syntax goes further to make the format understandable to others. In the future this similarity could be used to extend existing HTML editors/analyzers to support HTML::Template.

An advantage of this module over home-grown tag-replacement schemes is the support for loops. In my work I am often called on to produce tables of data in html. Producing them using simplistic HTML templates results in CGIs containing lots of HTML since the HTML itself cannot represent loops. The introduction of loop statements in the HTML simplifies this situation considerably. The designer can layout a single row and the programmer can fill it in as many times as necessary - all they must agree on is the parameter names.

For all that, I think the best thing about this module is that it does just one thing and it does it quickly and carefully. It doesn't try to replace Perl and HTML, it just augments them to interact a little better. And it's pretty fast.

The <TMPL_VAR> tag is very simple. For each <TMPL_VAR> tag in the template you call $template->param(PARAMETER_NAME => "VALUE"). When the template is output the <TMPL_VAR> is replaced with the VALUE text you specified. If you don't set a parameter it just gets skipped in the output.

Optionally you can use the "ESCAPE=HTML" option in the tag to indicate that you want the value to be HTML-escaped before being returned from output (the old ESCAPE=1 syntax is still supported). This means that the ", <, >, and & characters get translated into &quot;, &lt;, &gt; and &amp; respectively. This is useful when you want to use a TMPL_VAR in a context where those characters would cause trouble. Example:

You'll get what you wanted no matter what value happens to be passed in for param. You can also write ESCAPE="HTML", ESCAPE='HTML' and ESCAPE='1'. Substitute a 0 for the HTML and you turn off escaping, which is the default anyway.

The <TMPL_LOOP> tag is a bit more complicated than <TMPL_VAR>. The <TMPL_LOOP> tag allows you to delimit a section of text and give it a name. Inside this named loop you place <TMPL_VAR>s. Now you pass to param() a list (an array ref) of parameter assignments (hash refs) for this loop. The loop iterates over the list and produces output from the text block for each pass. Unset parameters are skipped. Here's an example

Inside a <TMPL_LOOP>, the only variables that are usable are the ones from the <TMPL_LOOP>. The variables in the outer blocks are not visible within a template loop. For the computer-science geeks among you, a <TMPL_LOOP> introduces a new scope much like a perl subroutine call. If you want your variables to be global you can use 'global_vars' option to new() described below.

This tag includes a template directly into the current template at the point where the tag is found. The included template contents are used exactly as if its contents were physically included in the master template.

The file specified can be an absolute path (beginning with a '/' under Unix, for example). If it isn't absolute, the path to the enclosing file is tried first. After that the path in the environment variable HTML_TEMPLATE_ROOT is tried, if it exists. Next, the "path" option is consulted, first as-is and then with HTML_TEMPLATE_ROOT prepended if available. As a final attempt, the filename is passed to open() directly. See below for more information on HTML_TEMPLATE_ROOT and the "path" option to new().

As a protection against infinitly recursive includes, an arbitary limit of 10 levels deep is imposed. You can alter this limit with the "max_includes" option. See the entry for the "max_includes" option below for more details.

The <TMPL_IF> tag allows you to include or not include a block of the template based on the value of a given parameter name. If the parameter is given a value that is true for Perl - like '1' - then the block is included in the output. If it is not defined, or given a false value - like '0' - then it is skipped. The parameters are specified the same way as with TMPL_VAR.

<TMPL_IF LOOP_ONE>
This will output if the loop is not empty.
</TMPL_IF>
<TMPL_LOOP LOOP_ONE>
....
</TMPL_LOOP>

WARNING: Much of the benefit of HTML::Template is in decoupling your Perl and HTML. If you introduce numerous cases where you have TMPL_IFs and matching Perl if()s, you will create a maintenance problem in keeping the two synchronized. I suggest you adopt the practice of only using TMPL_IF if you can do so without requiring a matching if() in your Perl code.

If you're a fanatic about valid HTML and would like your templates to conform to valid HTML syntax, you may optionally type template tags in the form of HTML comments. This may be of use to HTML authors who would like to validate their templates' HTML syntax prior to HTML::Template processing, or who use DTD-savvy editing tools.

You must call new() with at least one name => value pair specifying how to access the template text. You can use "filename => 'file.tmpl'" to specify a filename to be opened as the template. Alternately you can use:

These initialize the template from in-memory resources. In almost every case you'll want to use the filename parameter. If you're worried about all the disk access from reading a template file just use mod_perl and the cache option detailed below.

If the environment variable HTML_TEMPLATE_ROOT is set and your filename doesn't begin with /, then the path will be relative to the value of $HTML_TEMPLATE_ROOT. Example - if the environment variable HTML_TEMPLATE_ROOT is set to "/home/sam" and I call HTML::Template->new() with filename set to "sam.tmpl", the HTML::Template will try to open "/home/sam/sam.tmpl" to access the template file. You can also affect the search path for files with the "path" option to new() - see below for more information.

vanguard_compatibility_mode - if set to 1 the module will expect to see <TMPL_VAR>s that look like %NAME% in addition to the standard syntax. Also sets die_on_bad_params => 0. If you're not at Vanguard Media trying to use an old format template don't worry about this one. Defaults to 0.

cache - if set to 1 the module will cache in memory the parsed templates based on the filename parameter and modification date of the file. This only applies to templates opened with the filename parameter specified, not scalarref or arrayref templates. Caching also looks at the modification times of any files included using <TMPL_INCLUDE> tags, but again, only if the template is opened with filename parameter.

This is mainly of use in a persistent environment like Apache/mod_perl. It has absolutely no benefit in a normal CGI environment since the script is unloaded from memory after every request. For a cache that does work for normal CGIs see the 'shared_cache' option below.

Note that different new() parameter settings do not cause a cache refresh, only a change in the modification time of the template will trigger a cache refresh. For most usages this is fine. My simplistic testing shows that using cache yields a 90% performance increase under mod_perl. Cache defaults to 0.

shared_cache - if set to 1 the module will store its cache in shared memory using the IPC::SharedCache module (available from CPAN). The effect of this will be to maintain a single shared copy of each parsed template for all instances of HTML::Template to use. This can be a significant reduction in memory usage in a multiple server environment. As an example, on one of our systems we use 4MB of template cache and maintain 25 httpd processes - shared_cache results in saving almost 100MB! Of course, some reduction in speed versus normal caching is to be expected. Another difference between normal caching and shared_cache is that shared_cache will work in a CGI environment - normal caching is only useful in a persistent environment like Apache/mod_perl.

By default HTML::Template uses the IPC key 'TMPL' as a shared root segment (0x4c504d54 in hex), but this can be changed by setting the 'ipc_key' new() parameter to another 4-character or integer key. Other options can be used to affect the shared memory cache correspond to IPC::SharedCache options - ipc_mode, ipc_segment_size and ipc_max_size. See IPC::SharedCache for a description of how these work - in most cases you shouldn't need to change them from the defaults.

double_cache - if set to 1 the module will use a combination of shared_cache and normal cache mode for the best possible caching. Of course, it also uses the most memory of all the cache modes. All the same ipc_* options that work with shared_cache apply to double_cache as well. By default double_cache is off.

blind_cache - if set to 1 the module behaves exactly as with normal caching but does not check to see if the file has changed on each request. This option should be used with caution, but could be of use on high-load servers. My tests show blind_cache performing only 1 to 2 percent faster than cache under mod_perl.

NOTE: Combining this option with shared_cache can result in stale templates stuck permanently in shared memory!

注意: このオプションを shared_cache と組み合わせると、 共有メモリに古いテンプレートが永遠にたまってしまうかもしれません!

file_cache - if set to 1 the module will store its cache in a file using the Storable module. It uses no additional memory, and my simplistic testing shows that it yields a 50% performance advantage. Like shared_cache, it will work in a CGI environment. Default is 0.

file_cache_dir - sets the directory where the module will store the cache files if file_cache is enabled. Your script will need write permissions to this directory. You'll also need to make sure the sufficient space is available to store the cache files.

file_cache_dir_mode - sets the file mode for newly created file_cache directories and subdirectories. Defaults to 0700 for security but this may be inconvenient if you do not have access to the account running the webserver.

double_file_cache - if set to 1 the module will use a combination of file_cache and normal cache mode for the best possible caching. The file_cache_* options that work with file_cache apply to double_file_cache as well. By default double_file_cache is 0.

path - you can set this variable with a list of paths to search for files specified with the "filename" option to new() and for files included with the <TMPL_INCLUDE> tag. This list is only consulted when the filename is relative. The HTML_TEMPLATE_ROOT environment variable is always tried first if it exists. Also, if HTML_TEMPLATE_ROOT is set then an attempt will be made to prepend HTML_TEMPLATE_ROOT onto paths in the path array. In the case of a <TMPL_INCLUDE> file, the path to the including file is also tried before path is consulted.

NOTE: the paths in the path list must be expressed as UNIX paths, separated by the forward-slash character ('/').

注意: path リストでのパスは UNIX パスのように、 スラッシュ文字('/')で区切られて、表現されなければなりません。

search_path_on_include - if set to a true value the module will search from the top of the array of paths specified by the path option on every <TMPL_INCLUDE> and use the first matching template found. The normal behavior is to look only in the current directory for a template to include. Defaults to 0.

associate - this option allows you to inherit the parameter values from other objects. The only requirement for the other object is that it have a param() method that works like HTML::Template's param(). A good candidate would be a CGI.pm query object. Example:

The old associateCGI() call is still supported, but should be considered obsolete.

古い associateCGI() 呼び出しはまだサポートされていますが、 もう古いものだと考えるべきです。

NOTE: The parameter names are matched in a case-insensitve manner. If you have two parameters in a CGI object like 'NAME' and 'Name' one will be chosen randomly by associate. This behavior can be changed by the following option.

case_sensitive - setting this option to true causes HTML::Template to treat template variable names case-sensitively. The following example would only set one parameter without the "case_sensitive" option:

loop_context_vars - when this parameter is set to true (it is false by default) four loop context variables are made available inside a loop: __first__, __last__, __inner__, __odd__. They can be used with <TMPL_IF>, <TMPL_UNLESS> and <TMPL_ELSE> to control how a loop is output.

In addition to the above, a __counter__ var is also made available when loop context variables are turned on.

上記に加えて、ループコンテキスト変数が有効な場合は、 __counter__ 変数も利用可能になります。

Example:

例えば：

<TMPL_LOOP NAME="FOO">
<TMPL_IF NAME="__first__">
This only outputs on the first pass.
</TMPL_IF>
<TMPL_IF NAME="__odd__">
This outputs every other pass, on the odd passes.
</TMPL_IF>
<TMPL_UNLESS NAME="__odd__">
This outputs every other pass, on the even passes.
</TMPL_IF>
<TMPL_IF NAME="__inner__">
This outputs on passes that are neither first nor last.
</TMPL_IF>
This is pass number <TMPL_VAR NAME="__counter__">.
<TMPL_IF NAME="__last__">
This only outputs on the last pass.
<TMPL_IF>
</TMPL_LOOP>

One use of this feature is to provide a "separator" similar in effect to the perl function join(). Example:

max_includes - set this variable to determine the maximum depth that includes can reach. Set to 10 by default. Including files to a depth greater than this value causes an error message to be displayed. Set to 0 to disable this protection.

global_vars - normally variables declared outside a loop are not available inside a loop. This option makes <TMPL_VAR>s like global variables in Perl - they have unlimited scope. This option also affects <TMPL_IF> and <TMPL_UNLESS>.

This is a normal variable: <TMPL_VAR NORMAL>.<P>
<TMPL_LOOP NAME=FROOT_LOOP>
Here it is inside the loop: <TMPL_VAR NORMAL><P>
</TMPL_LOOP>

Normally this wouldn't work as expected, since <TMPL_VAR NORMAL>'s value outside the loop is not available inside the loop.

通常これは、ループの外にある <TMPL_VAR NORMAL> の値が ループの内側では使えないために、期待した通りには動きません。

The global_vars option also allows you to access the values of an enclosing loop within an inner loop. For example, in this loop the inner loop will have access to the value of OUTER_VAR in the correct iteration:

filter - this option allows you to specify a filter for your template files. A filter is a subroutine that will be called after HTML::Template reads your template file but before it starts parsing template tags.

In the most simple usage, you simply assign a code reference to the filter parameter. This subroutine will recieve a single arguement - a reference to a string containing the template file text. Here is an example that accepts templates with tags that look like "!!!ZAP_VAR FOO!!!" and transforms them into HTML::Template tags:

More complicated usages are possible. You can request that your filter receieve the template text as an array of lines rather than as a single scalar. To do that you need to specify your filter using a hash-ref. In this form you specify the filter using the "sub" key and the desired argument format using the "format" key. The available formats are "scalar" and "array". Using the "array" format will incur a performance penalty but may be more convenient in some situations.

You may also have multiple filters. This allows simple filters to be combined for more elaborate functionality. To do this you specify an array of filters. The filters are applied in the order they are specified.

output() returns the final result of the template. In most situations you'll want to print this, like:

output() はテンプレートの最終結果を返します。 ほとんどの場合、以下のようにこれを出力したいでしょう:

print $template->output();

When output is called each occurrence of <TMPL_VAR NAME=name> is replaced with the value assigned to "name" via param(). If a named parameter is unset it is simply replaced with ''. <TMPL_LOOPS> are evaluated once per parameter set, accumlating output on each pass.

This method allow you to get information about the template structure. It can be called in a number of ways. The simplest usage of query is simply to check whether a parameter name exists in the template, using the name option:

As you can see above the loop option returns a list of parameter names and both name and loop take array refs in order to refer to parameters inside loops. It is an error to use loop with a parameter that is not a loop.

If you just want to get email when new releases are available you can join the announcements mailing-list here:

新しいリリースが出たのを知りたいだけなら、アナウンス用の メーリングリストもあります:

http://lists.sourceforge.net/lists/listinfo/html-template-announce

Q: Is there a searchable archive for the mailing-list?

Q; 検索可能なメーリングリストのアーカイブはありますか?

A: Yes, you can find an archive of the SourceForge list here:

はい、SourceForge メーリングリストのアーカイブが以下の場所にあります:

http://www.geocrawler.com/lists/3/SourceForge/23294/0/

For an archive of the old vm.com list, setup by Sean P. Scanlon, see:

古い vm.com 時代のメーリングリストのアーカイブは、 Sean P. Scanlon が設定したものが以下の場所にあります:

http://bluedot.net/mail/archive/

Q: I want support for <TMPL_XXX>! How about it?

Q: <TMPL_XXX> に対応してほしいんです!どうすればいいんでしょう?

A: Maybe. I definitely encourage people to discuss their ideas for HTML::Template on the mailing list. Please be ready to explain to me how the new tag fits in with HTML::Template's mission to provide a fast, lightweight system for using HTML templates.

A: Simple - the case-insensitive match switch is very inefficient. According to _Mastering_Regular_Expressions_ from O'Reilly Press, /[Tt]/ is faster and more space efficient than /t/i - by as much as double against long strings. //i essentially does a lc() on the string and keeps a temporary copy in memory.

Note that you'll need to modify the "return unless" line to specify the extension you use for your template files - I use .tmpl, as you can see. You'll also need to specify the path to your template files.

One potential problem: the "/path/to/templates/" must be EXACTLY the same path you use when you call HTML::Template->new(). Otherwise the cache won't know they're the same file and will load a new copy - instead getting a speed increase, you'll double your memory usage. To find out if this is happening set cache_debug => 1 in your application code and look for "CACHE MISS" messages in the logs.

But, inevitably some people still want to do it. If that describes you then you should take a look at HTML::Template::Expr. Using HTML::Template::Expr it should be easy to write a run_program() function. Then you can do awful stuff like:

Just, please, don't tell me about it. I'm feeling guilty enough just for writing HTML::Template::Expr in the first place.

Q: Can I get a copy of these docs in Japanese?

A: Yes you can. See Kawai Takanori's translation at:

http://member.nifty.ne.jp/hippo2000/perltips/html/template.htm

Q: What's the best way to create a <select> form element using HTML::Template?

A: There is much disagreement on this issue. My personal preference is to use CGI.pm's excellent popup_menu() and scrolling_list() functions to fill in a single <tmpl_var select_foo> variable.

To some people this smacks of mixing HTML and code in a way that they hoped HTML::Template would help them avoid. To them I'd say that HTML is a violation of the principle of separating design from programming. There's no clear separation between the programmatic elements of the <form> tags and the layout of the <form> tags. You'll have to draw the line somewhere - clearly the designer can't be entirely in charge of form creation.

It's a balancing act and you have to weigh the pros and cons on each side. It is certainly possible to produce a <select> element entirely inside the template. What you end up with is a rat's nest of loops and conditionals. Alternately you can give up a certain amount of flexibility in return for vastly simplifying your templates. I generally choose the latter.

Another option is to investigate HTML::FillInForm which some have reported success using to solve this problem.

HTML::Template : A module for using HTML Templates with Perl
Copyright (C) 2000-2002 Sam Tregar (sam@tregar.com)
This module is free software; you can redistribute it and/or modify it
under the terms of either:
a) the GNU General Public License as published by the Free Software
Foundation; either version 1, or (at your option) any later version,
or
b) the "Artistic License" which comes with this module.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either
the GNU General Public License or the Artistic License for more details.
You should have received a copy of the Artistic License with this
module, in the file ARTISTIC. If not, I'll be glad to provide one.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA