Use template perl




















Inside the array are any number of hash references. The variables in the outer blocks are not visible within a template loop. 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. If it isn't absolute, the path to the enclosing file is tried first. As a final attempt, the filename is passed to open directly. As a protection against infinitely recursive includes, an arbitrary limit of 10 levels deep is imposed. 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. However, they are allowed to "break the rules". Something like:. In order to realize a dramatic savings in bandwidth, the standard non-comment tags will be used throughout this documentation.

Alternately you can use:. These initialize the template from in-memory resources. In almost every case you'll want to use the filename parameter. You can also read the template from an already opened filehandle, either traditionally as a glob or as a FileHandle :. 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.

The options are available:. If set to 1 the module will not allow you to set unescaped parameters with tainted values. If set to 2 you will have to untaint all parameters, including ones with the escape attribute.

This option makes sure you untaint everything so you don't accidentally introduce e. Requires taint mode. Defaults to 0. Defaults to 1. If you're not at Vanguard Media trying to use an old format template don't worry about this one.

If set to 1 the module will cache in memory the parsed templates based on the filename parameter, the modification date of the file and the options passed to new. This only applies to templates opened with the filename parameter specified, not scalarref or arrayref templates.

It has absolutely no benefit in a normal CGI environment since the script is unloaded from memory after every request. Cache defaults to 0. The effect of this will be to maintain a single shared copy of each parsed template for all instances of HTML::Template on the same machine to use.

This can be a significant reduction in memory usage in an environment with a single machine but multiple servers. Of course, some reduction in speed versus normal caching is to be expected. See IPC::SharedCache for a description of how these work - in most cases you shouldn't need to change them from the defaults. Of course, it also uses the most memory of all the cache modes. 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. If set to 1 the module will store its cache in a file using the Storable module.

Default is 0. See below for details. The html filter is an example of a static filter, implemented as:. Dynamic filters can accept arguments which are specified when the filter is called from a template. The repeat filter is such an example, accepting a numerical argument which specifies the number of times that the input text should be repeated. These are implemented as filter 'factories'. The factory subroutine is passed a reference to the current Template::Context object along with any additional arguments specified.

It should then return a subroutine reference e. The repeat filter factory is implemented like this:. When using a filter, it is possible to assign an alias to it for further use. This is most useful for dynamic filters that you want to re-use with the same configuration. A template variable can also be used to define a static filter subroutine. However, the Template Toolkit will automatically call any subroutine bound to a variable and use the value returned.

Thus, the above example could be implemented as:. To define a template variable that evaluates to a subroutine reference that can be used by the FILTER directive, you should create a subroutine that, when called automatically by the Template Toolkit, returns another subroutine reference which can then be used to perform the filter operation.

Note that only static filters can be implemented in this way. Alternately, you can bless a subroutine reference into a class any class will do to fool the Template Toolkit into thinking it's an object rather than a subroutine.

This will then bypass the automatic "call-a-subroutine-to-return-a-value" magic. Filters bound to template variables remain local to the variable context in which they are defined. That is, if you define a filter in a PERL block within a template that is loaded via INCLUDE , then the filter definition will only exist until the end of that template when the stash is delocalised, restoring the previous variable state. See Template::Manual::Filters for a complete list of available filters, their descriptions and examples of use.

The USE directive can be used to load and initialise "plugin" extension modules. A plugin is a regular Perl module that conforms to a particular object-oriented interface, allowing it to be loaded into and used automatically by the Template Toolkit.

For details of this interface and information on writing plugins, consult Template::Plugin. A number of standard plugins are included with the Template Toolkit see below and Template::Manual::Plugins. The names of these standard plugins are case insensitive. The recommended convention is to specify these plugin names in lower case. The Template Toolkit first looks for an exact case-sensitive match and then tries the lower case conversion of the name specified.

In this case the plugin name is case-sensitive. Any periods, '. If a regular Perl module i. The following trivial example shows how the IO::File module might be used. Any additional parameters supplied in parenthesis after the plugin name will be also be passed to the new constructor. A reference to the current Template::Context object is passed as the first parameter. This is based on the assumption that the module is a regular Perl module rather than a Template Toolkit plugin so isn't expecting a context reference and wouldn't know what to do with it anyway.

Named parameters may also be specified. These are collated into a hash which is passed by reference as the last parameter to the constructor, as per the general code calling interface.

The plugin may represent any data type; a simple variable, hash, list or code reference, but in the general case it will be an object reference. Methods can be called on the object or the relevant members of the specific data type in the usual way:. An alternative name may be provided for the plugin by which it can be referenced:. You can use this approach to create multiple plugin objects with different configurations.

This example shows how the format plugin is used to create sub-routines bound to variables for formatting text as per printf. This next example shows how the URL plugin can be used to build dynamic URLs from a base part and optional query parameters.

The CGI plugin is an example of one which delegates to another Perl module. All of the methods provided by the CGI module are available via the plugin. The MACRO directive allows you to define a directive or directive block which is then evaluated each time the macro is called. Macros can be passed named parameters when called.

These values remain local to the macro. Values passed to the macros are then mapped to these local variables. Other named parameters may follow these. Here's another example, defining a macro for display numbers in comma-delimited groups of 3, using the chunk and join virtual method. The block will be evaluated each time the macro is called. Perl code is evaluated in the Template::Perl package. This can be used to access the functionality of the Template Toolkit to process other templates, load plugins, filters, etc.

See Template::Context for further details. Through this, variable values can be retrieved and updated. The problem is the same as if you had written a subroutine that used those variables in the same way that the template does. If the template does this, you are safe. Templates cannot affect variables in the main program that are declared with my , unless you give the template references to those variables. You may not want to put the template variables into a package.

Packages can be hard to manage: You can't copy them, for example. HASH provides an alternative. The value for HASH should be a reference to a hash that maps variable names to values. For example,. Note that we pass an array reference, but inside the template it appears as an array. In general, anything other than a simple string or number should be passed by reference. The full details of how it works are a little involved, so you might want to skip to the next section.

If the value is a reference to an array, then key is set to that array. Similarly if value is any other kind of reference. This means that. The difference is that in the former case, the value is copied, and in the latter case it is aliased. In particular, if you want the template to get an object or any kind, you must pass a reference to it:.

Normally, the way this works is by allocating a private package, loading all the variables into the package, and then filling out the template as if you had specified that package. A new package is allocated each time. If the argument of HASH is a reference to an array instead of a reference to a hash, then the array should contain a list of hashes whose contents are loaded into the template package one after the other.

You can use this feature if you want to combine several sets of variables. For example, one set of variables might be the defaults for a fill-in form, and the second set might be the user inputs, which override the defaults when they are present:. If any of the program fragments fails to compile or aborts for any reason, and you have set the BROKEN option to a function reference, Text::Template will invoke the function.

If the BROKEN function returns undef , Text::Template will immediately abort processing the template and return the text that it has accumulated so far. If the BROKEN function returns any other value, that value will be interpolated into the template as if that value had been the return value of the program fragment to begin with. For example, if the BROKEN function returns an error string, the error string will be interpolated into the output of the template in place of the program fragment that cased the error.

Note that the format of this message has changed slightly since version 1. The return value of the BROKEN function is interpolated into the template at the place the error occurred, so that this template:. The hash will have at least these three members:. The text has been modified to omit the trailing newline and to include the name of the template file if there was one. The line number counts from the beginning of the template, not from the beginning of the failed program fragment.

For example:. This only affects the error message that is given for template errors. If you loaded the template from foo. Note that this does NOT have anything to do with loading a template from the given filename.

All evaluation of program fragments will be performed in this compartment. See Safe for full details about such compartments and how to restrict the operations that can be performed in them. If not, SAFE operation is a little different from the default. Usually, if you don't specify a package, evaluation of program fragments occurs in the package from which the template was invoked. But in SAFE mode the evaluation occurs inside the safe compartment and cannot affect the calling package.

If your template is going to generate a lot of text that you are just going to print out again anyway, you can save memory by having Text::Template print out the text as it is generated instead of making it into a big string and returning the string. The generated text will be printed to this filehandle as it is constructed. This may result in the output appearing more quickly than it would have otherwise. You can have some Perl code prepended automatically to the beginning of every program fragment.

If this option is present, its value should be a reference to a list of two strings. This is useful if you want to fill in the same template more than once. In some programs, this can be cumbersome. It constructs the template object for you, fills it in as specified, and returns the results. It is only here for backwards compatibility, and may be removed in some far-future version in Text::Template. It is described in the next section. But I made the mistake four years ago and it is too late to change it.

The filename is the name of the file that contains the template you want to fill in. It returns the result text. It will be a lot faster because it only has to read and parse the file once. People always ask for this. The short answer is this is Perl, and Perl already has an include function. If you want it, you can just put.

If you don't want to use cat , you can write a little four-line function that opens a file and dumps out its contents, and call it from the template. I wrote one for you. In the template, you can say. This is a mature package that has evolved to handle real-world problems. One thing to note about the session and state management in this system is that it currently only supports clusters through the use of network file systems such as NFS or SMB.

This may be an issue for large-scale server clusters, which usually rely on a relational database for network storage of sessions. Support for database storage of sessions is planned in a future release. In the meantime, instructions are provided for hooking up to Apache::Session. This module has become the de facto standard general purpose templating module on CPAN.

It has an easy interface and thorough documentation. The module uses in-line Perl. It has the ability to run the in-line code in a Safe compartment, in case you are concerned about mistakes in the code crashing your server. The module relies on creative uses of in-line code to provide things that people usually expect from templating tools, like includes.

This can be good or bad. Most of the fancier templating tools have concepts like include paths, which allow you to specify a list of directories to search for included files. Each template is loaded as a separate object. Templates are compiled to Perl and only parsed the first time they are used. It is perfectly at home generating e-mails, PDFs, etc. One of the more recent additions to the templating scene, Template Toolkit, is a flexible mini-language system.

It has a complete set of directives for working with data, including loops and conditionals, and it can be extended in a number of ways. In-line Perl code can be enabled with a configuration option, but is generally discouraged.

It uses compilation, caching the compiled bytecode in memory and optionally caching the generated Perl code for templates on disk. Although it is commonly used in a pipeline style, the included Apache::Template module allows templates to be invoked directly from URLs. One major difference between TT and other systems is that it provides simple access to complex data structures through the concept of a dot operator.

For example, we could pass in this Perl data structure:. This is simpler and more uniform than the equivalent syntax in Perl. If we pass in an object as part of the data structure, we can use the same notation to call methods within that object. Templates can define macros and include other templates, and parameters can be passed to either. Included templates can optionally localize their variables so that changes made while the included template is executing do not affect the values of variables in the larger scope.

There is a filter directive, which can be used for post-processing output. TT supports a plugin API, which can be used to add extra capabilities to your templates. The provided plug-ins can be broadly organized into data access and formatting. Standard data access plugins include modules for accessing XML data or a DBI data source and using that data within your template.

Formatting plug-ins allow you to display things like dates and prices in a localized style. These formatting plug-ins do a good job of covering the final 5 percent of data display problems that often cause people who are using an in-house system to embed a little bit of HTML in their Perl modules. In a similar vein, TT includes some nice convenience features for template writers, including eliminating white space around tags and the ability to change the tag delimiters — things that may sound a little esoteric, but can sometimes make templates significantly easier to use.

The TT distribution also includes a script called ttree, which allows for processing an entire directory tree of templates. This is useful for sites that pre-publish their templated pages and serve them statically. The script checks modification times and only updates pages that require it, providing a make-like functionality. The distribution also includes a sample set of template-driven HTML widgets that can be used to give a consistent look and feel to a collection of documents.

HTML::Template is a popular module among those looking to use a mini-language rather than in-line Perl. It uses a simple set of tags that allow looping even on nested data structures and conditionals in addition to basic value insertion. The tags are intentionally styled to look like HTML tags, which may be useful for some situations. The module follows a pipeline execution style. Parsed templates are stored in a Perl data structure that can be cached in any combination of memory, shared memory using IPC::SharedCache and disk.

The documentation is complete and well-written, with plenty of examples. You may be wondering how this module is different from Template Toolkit, the other popular mini-language system. Beyond the obvious differences in syntax, HTML::Template is faster and simpler, while Template Toolkit has more advanced features, like plug-ins and dot notation.

This allows it to use genuine valid HTML documents as templates, something that none of these other modules can do. The learning curve is a little steeper than average, but this may be just the thing if you are concerned about keeping things simple for your HTML coders. XPP is an in-line Perl system that compiles to bytecode.

Although it is a perfectly good implementation, it has little to differentiate it except for an easy mechanism to define new HTML-like tags that can be used to replace in-line code in templates. It caches compiled bytecode in memory to achieve solid performance, and some people find it refreshingly simple to use. This module takes a minimalistic approach to templating, which makes it unusually well-suited to use in CGI programs.

It parses templates with a single regular expression and does not support anything in templates beyond simple variable interpolation. Loops are handled by including the output of other templates. Unfortunately, this leads to a Perl coding style that is more confusing than most, and a proliferation of template files. However, some people swear by this dirt-simple approach. People always seem to worry about the performance of templating systems.

Compared to such glacially slow operations as fetching data from a database or file, the time added by the templating system is almost negligible. If you think your templating system is slowing you down, get the facts: pull out Devel::DProf and see. Personally, I have only seen this happen when I had managed to successfully cache nearly every part of the work to handle a request except running a template. However, if you really are in a situation where you need to squeeze a few extra microseconds out of your page generation time, there are performance differences between systems.



0コメント

  • 1000 / 1000