📄 template.pm
字号:
</TMPL_LOOP>=cut=head1 Methods=head2 new()Call new() to create a new Template object: my $template = HTML::Template->new( filename => 'file.tmpl', option => 'value' );You must call new() with at least one name => value pair specifying howto access the template text. You can use "filename => 'file.tmpl'" tospecify a filename to be opened as the template. Alternately you canuse: my $t = HTML::Template->new( scalarref => $ref_to_template_text, option => 'value' );and my $t = HTML::Template->new( arrayref => $ref_to_array_of_lines , option => 'value' );These initialize the template from in-memory resources. In almostevery case you'll want to use the filename parameter. If you'reworried about all the disk access from reading a template file justuse mod_perl and the cache option detailed below.You can also read the template from an already opened filehandle,either traditionally as a glob or as a FileHandle: my $t = HTML::Template->new( filehandle => *FH, option => 'value');The four new() calling methods can also be accessed as below, if youprefer. my $t = HTML::Template->new_file('file.tmpl', option => 'value'); my $t = HTML::Template->new_scalar_ref($ref_to_template_text, option => 'value'); my $t = HTML::Template->new_array_ref($ref_to_array_of_lines, option => 'value'); my $t = HTML::Template->new_filehandle($fh, option => 'value');And as a final option, for those that might prefer it, you can call new as: my $t = HTML::Template->new(type => 'filename', source => 'file.tmpl');Which works for all three of the source types.If the environment variable HTML_TEMPLATE_ROOT is set and yourfilename doesn't begin with /, then the path will be relative to thevalue of $HTML_TEMPLATE_ROOT. Example - if the environment variableHTML_TEMPLATE_ROOT is set to "/home/sam" and I callHTML::Template->new() with filename set to "sam.tmpl", theHTML::Template will try to open "/home/sam/sam.tmpl" to access thetemplate file. You can also affect the search path for files with the"path" option to new() - see below for more information.You can modify the Template object's behavior with new. These optionsare available:=over 4=item *die_on_bad_params - if set to 0 the module will let you call$template->param(param_name => 'value') even if 'param_name' doesn'texist in the template body. Defaults to 1.=item *strict - if set to 0 the module will allow things that look like they might be TMPL_* tags to get by without dieing. Example: <TMPL_HUH NAME=ZUH>Would normally cause an error, but if you call new with strict => 0,HTML::Template will ignore it. Defaults to 1.=item *cache - if set to 1 the module will cache in memory the parsedtemplates based on the filename parameter and modification date of thefile. This only applies to templates opened with the filenameparameter specified, not scalarref or arrayref templates. Cachingalso looks at the modification times of any files included using<TMPL_INCLUDE> tags, but again, only if the template is opened withfilename parameter. This is mainly of use in a persistent environment likeApache/mod_perl. It has absolutely no benefit in a normal CGIenvironment since the script is unloaded from memory after everyrequest. 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 cacherefresh, only a change in the modification time of the template willtrigger a cache refresh. For most usages this is fine. My simplistictesting shows that using cache yields a 90% performance increase undermod_perl. Cache defaults to 0.=item *shared_cache - if set to 1 the module will store its cache in sharedmemory using the IPC::SharedCache module (available from CPAN). Theeffect of this will be to maintain a single shared copy of each parsedtemplate for all instances of HTML::Template to use. This can be asignificant reduction in memory usage in a multiple serverenvironment. As an example, on one of our systems we use 4MB oftemplate cache and maintain 25 httpd processes - shared_cache resultsin saving almost 100MB! Of course, some reduction in speed versusnormal caching is to be expected. Another difference between normalcaching and shared_cache is that shared_cache will work in a CGIenvironment - normal caching is only useful in a persistentenvironment like Apache/mod_perl.By default HTML::Template uses the IPC key 'TMPL' as a shared rootsegment (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 correspondto IPC::SharedCache options - ipc_mode, ipc_segment_size andipc_max_size. See L<IPC::SharedCache> for a description of how thesework - in most cases you shouldn't need to change them from thedefaults.For more information about the shared memory cache system used byHTML::Template see L<IPC::SharedCache>.=item *double_cache - if set to 1 the module will use a combination ofshared_cache and normal cache mode for the best possible caching. Ofcourse, it also uses the most memory of all the cache modes. All thesame ipc_* options that work with shared_cache apply to double_cacheas well. By default double_cache is off.=item *blind_cache - if set to 1 the module behaves exactly as with normalcaching but does not check to see if the file has changed on eachrequest. This option should be used with caution, but could be of useon high-load servers. My tests show blind_cache performing only 1 to2 percent faster than cache under mod_perl.NOTE: Combining this option with shared_cache can result in staletemplates stuck permanently in shared memory!=item *file_cache - if set to 1 the module will store its cache in a fileusing the Storable module. It uses no additional memory, and mysimplistic testing shows that it yields a 50% performance advantage.Like shared_cache, it will work in a CGI environment. Default is 0.If you set this option you must set the "file_cache_dir" option. Seebelow for details.NOTE: Storable using flock() to ensure safe access to cache files.Using file_cache on a system or filesystem (NFS) without flock()support is dangerous.=item *file_cache_dir - sets the directory where the module will store thecache files if file_cache is enabled. Your script will need writepermissions to this directory. You'll also need to make sure thesufficient space is available to store the cache files.=item *file_cache_dir_mode - sets the file mode for newly created file_cachedirectories and subdirectories. Defaults to 0700 for security butthis may be inconvenient if you do not have access to the accountrunning the webserver.=item *double_file_cache - if set to 1 the module will use a combination offile_cache and normal cache mode for the best possible caching. Thefile_cache_* options that work with file_cache apply to double_file_cacheas well. By default double_file_cache is 0.=item *associate - this option allows you to inherit the parameter valuesfrom other objects. The only requirement for the other object is thatit have a param() method that works like HTML::Template's param(). Agood candidate would be a CGI.pm query object. Example: my $query = new CGI; my $template = HTML::Template->new(filename => 'template.tmpl', associate => $query);Now, $template->output() will act as though $template->param('FormField', $cgi->param('FormField'));had been specified for each key/value pair that would be provided bythe $cgi->param() method. Parameters you set directly take precedenceover associated parameters. You can specify multiple objects to associate by passing an anonymousarray to the associate option. They are searched for parameters inthe order they appear: my $template = HTML::Template->new(filename => 'template.tmpl', associate => [$query, $other_obj]);The old associateCGI() call is still supported, but should beconsidered obsolete.NOTE: The parameter names are matched in a case-insensitve manner. Ifyou have two parameters in a CGI object like 'NAME' and 'Name' onewill be chosen randomly by associate. This behavior can be changed bythe following option.=item *case_sensitive - setting this option to true causes HTML::Template totreat template variable names case-sensitively. The following examplewould only set one parameter without the "case_sensitive" option: my $template = HTML::Template->new(filename => 'template.tmpl', case_sensitive => 1); $template->param( FieldA => 'foo', fIELDa => 'bar', );This option defaults to off.=item *loop_context_vars - when this parameter is set to true (it is false bydefault) 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 isoutput. 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> <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 effectto the perl function join(). Example: <TMPL_LOOP FRUIT> <TMPL_IF __LAST__> and </TMPL_IF> <TMPL_VAR KIND><TMPL_UNLESS __LAST__>, <TMPL_ELSE>.</TMPL_UNLESS> </TMPL_LOOP>Would output (in a browser) something like: Apples, Oranges, Brains, Toes, and Kiwi.Given an appropriate param() call, of course. NOTE: A loop with onlya single pass will get both __FIRST__ and __LAST__ set to true, butnot __INNER__.=item *path - you can set this variable with a list of paths to search forfiles specified with the "filename" option to new() and for filesincluded with the <TMPL_INCLUDE> tag. This list is only consultedwhen the filename is relative. The HTML_TEMPLATE_ROOT environmentvariable is always tried first if it exists. In the case of a<TMPL_INCLUDE> file, the path to the including file is also triedbefore path is consulted.Example: my $template = HTML::Template->new( filename => 'file.tmpl', path => [ '/path/to/templates', '/alternate/path' ] );NOTE: the paths in the path list must be expressed as UNIX paths,separated by the forward-slash character ('/').=item *no_includes - set this option to 1 to disallow the <TMPL_INCLUDE> tagin the template file. This can be used to make opening untrustedtemplates B<slightly> less dangerous. Defaults to 0.=item *max_includes - set this variable to determine the maximum depth thatincludes can reach. Set to 10 by default. Including files to a depthgreater than this value causes an error message to be displayed. Setto 0 to disable this protection.=item *search_path_on_include - if set to a true value the module will searchfrom the top of the array of paths specified by the path option onevery <TMPL_INCLUDE> and use the first matching template found. Thenormal behavior is to look only in the current directory for atemplate to include. Defaults to 0.=item *global_vars - normally variables declared outside a loop are notavailable inside a loop. This option makes <TMPL_VAR>s like globalvariables in Perl - they have unlimited scope. This option alsoaffects <TMPL_IF> and <TMPL_UNLESS>.Example: 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>'svalue outside the loop is not available inside the loop.=item *filter - this option allows you to specify a filter for your templatefiles. A filter is a subroutine that will be called afterHTML::Template reads your template file but before it starts parsingtemplate tags.In the most simple usage, you simply assign a code reference to thefilter parameter. This subroutine will recieve a single arguement - areference to a string containing the template file text. Here is anexample that accepts templates with tags that look like "!!!ZAP_VARFOO!!!" and transforms them into HTML::Template tags: my $filter = sub { my $text_ref = shift; $$text_ref =~ s/!!!ZAP_(.*?)!!!/<TMPL_$1>/g; } # open zap.tmpl using the above filter my $template = HTML::Template->new(filename => 'zap.tmpl', filter => $filter);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -