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. Using in-line print statements is faster than using templates.
Using simple substitution is faster than using in-line Perl code. Using in-line Perl code is faster than using a mini-language.
It is available from the following URL:. Not all of the systems mentioned here are currently included in the test. If your favorite was missed, you might want to download the benchmark code and add it.
Nevertheless, some people are stuck with CGI but still want to use a templating system with reasonable performance. CGI is a tricky situation, since you have to worry about how much time it will take for Perl to compile the code for a large templating system on each request.
CGI also breaks the in-memory caching of templates used by most of these systems, although the slower disk-based caching provided by Mason, HTML::Template and Template Toolkit will still work. HTML::Template does provide a shared memory cache for templates, which may improve performance, although shared memory on my Linux system is usually slower than using the filesystem. Benchmarks and additional information are welcome.
Almost everything else mentioned here will add tenths of seconds to each page in compilation time alone. You should not eliminate options based on this chart without reading the more detailed explanations above. These modules are moving targets, and a document like this is bound to contain some mistakes. Send your corrections to perrin elem. Something wrong with this article?
Help us out by opening an issue or pull request on GitHub. To get in touch, send an email to perl. The information published on this website may not be suitable for every situation. All work on this website is provided with the understanding that Perl.
Neither Perl. Why Use Templates? Reusability Along the same lines, building a set of commonly used components makes it easier to create new pages. What Are the Differences? The sample copy above will be fine for simple testing purposes or internal error reporting. If you, however, want to send emails to your users or just want to make a better impression on Jane , you will want to use some HTML in the email body.
By default, sendmail sends emails in plain text. Note that each file will be loaded to the memory twice. So, adding large files is probably a poor idea. Before running the code below, make sure the Mail::Sendmail module is already installed. Test Your Emails Now. You get all of this, without sacrificing the simple process of sending emails.
This is a summary of the processing options, including the Source and Destination that we provided as the -s and -d command-line options. The dog and cat files are listed as the two files that ttree found in the templates directory.
Now that these templates have been processed, ttree will not process them again until they are modified or the corresponding output file is deleted.
By looking at the file modification times of the source template and destination file, ttree can decide which templates have changed and which have not. It saves time by processing only those that have changed.
These - characters indicate that the template files were not processed this time, with the reason given in parentheses to the right. This can save a great deal of time when building large document systems using templates e. The -a option forces ttree to process all templates, regardless of their modification times:.
A second benefit of ttree is that it offers numerous options for changing its behavior. Adding a standard header and footer to each page template, for example, is as easy as setting the relevant option:.
The number of options can be overwhelming at first, but in practice, only a few are used on a regular basis. To avoid having to always use the command line to specify options—something that can quickly become cumbersome and error prone, especially if you are using more than a few— ttree allows you to use configuration files to define all the options for a particular web site or other document system. You can then invoke ttree , passing the name of the configuration file using the -f option:.
Example shows a sample ttree configuration file. In the configuration file, the -s and -d options are represented by the src and dest options. We also added a lib option -l on the command line , which tells ttree about an additional library directory where our header and footer templates are found.
Setting up ttree is a little more involved than using tpage , but the effort quickly pays off in the time it saves you. We look at ttree in detail in Chapter 2 , showing everything from first-time use through writing and managing configuration files.
Both tpage and ttree use the Template Perl module to do the dirty work of processing templates. Chapter 7 goes into greater detail about what lurks beneath the hood of the Template Toolkit, but for now we cover just the basics.
If you are already a Perl hacker experienced in using modules, the Template manpage gives you an executive summary to get you quickly up to speed. Thanks to the tpage and ttree programs, you can build your entire web site or other template-based document system without ever having to write a line of Perl code.
Also, certain features are accessible only through Perl for example, the ability to define a subroutine to return the value for a variable , so there is a good chance that sooner or later you will want or need those Perl-specific features. Example shows a simple Perl program for processing the destruction. The first line defines the path to the Perl interpreter on your system. This is very much a Unix-specific convention. On a Windows machine, for example, this line is not relevant or required.
It is good Perl style to include use strict; and use warnings; at the top of every program, or to invoke Perl with the -w switch instead of use warnings; for versions of Perl earlier than 5.
These two precautions will catch many common programming and typographical errors, and warn you about any questionable practices. Perl examples in this book may omit them for brevity, but you should always include them in any nontrivial chunk of code.
The process method processes the template and returns a true value to indicate success. If an error occurs, the process method returns false. In this case, we call the error method to find out what went wrong and report it as a fatal error using die. An error can be returned for a number of reasons, such as the file specified could not be found, had embedded directives containing illegal syntax that could not be parsed, or generated a runtime error while the template was being processed.
Now we can see how these are used in the underlying Perl implementation. Configuration options are passed to the new constructor method as a reference to a hash, as shown in Example These are provided as a reference to a list of the two directory paths.
For this example, we are assuming that the destruction. The Template Toolkit provides numerous configuration options. These are described in detail in the Appendix. We describe the useful ones as we encounter them in later chapters. Example shows an extract of an httpd. Apache::Template adopts the Apache convention of using StudlyCaps for the names of configuration options and also adds a unique TT2 prefix. The two options that follow are specific to the Apache::Template handler:.
The first, TT2Params , provides a list of items that the handler should automatically extract from the Apache request and make available as template variables.
Any template can use the uri , env , params , and cookies variables to access the request URI, environment variables, request parameters, and cookies, respectively. The second directive, TT2Headers , indicates that Last-Modified and Content-Length headers should be automatically added to the response sent to the client. The final section uses the Apache Files directive to define the files that should be processed as templates:.
With this configuration, the Apache server processes any files with a. This is a convenient way of mixing static HTML pages with dynamic page templates in any directory that is currently accessible by the Apache web server.
If you want to create a static page, use a. If you want to create a dynamic page from a template, with the appropriate headers and footer added automatically, simply give it a. If you would rather not open up your entire web server to the Apache::Template module, you can instead use the Location directive. There are numerous other Apache configuration directives, all of which are described in the documentation provided with Apache.
For a full discussion of the Apache::Template configuration, see the Appendix. The Template Toolkit language is a presentation language rather than a general-purpose programming language. It provides the kind of features that you would expect to see in a regular programming language, including loops, conditional tests, and the ability to manipulate variable values. However, in this case they serve a slightly different purpose.
The Template Toolkit is designed for the task of generating content and presenting data, and it generally leaves more complex issues to a real programming language, namely, Perl.
We have already seen the basics of what a template looks like—a mixture of tags known as directives and other fixed text. The template processor interprets the directives and the remaining text is passed through unchanged. The TAGS directive takes either one or two arguments. The single-argument version expects the name of a predefined tag set. If you give TAGS two arguments, they define the start and end tag markers that you want to use.
In the rest of this book, we use the default tag style. We like it because it makes the directives stand out from the surrounding text, rather than making them blend in.
We think it makes templates easier to read and write when you can more clearly distinguish one part from another. The variables that we have used so far have been scalar variables. A scalar variable stores a single piece of information—either a string or a number.
The value of a scalar variable is inserted in a template by using the variable name inside a directive like this:. In addition to scalar variables, the Template Toolkit also supports two complex data types for storing multiple values: the list and hash array also known as a hash. A list is an ordered array of other variables, indexed numerically and starting at element 0. A hash is an unordered collection of other variables, which are indexed and accessible by a unique name or key.
Perl programmers will already be familiar with these data structures. When you use the Template Toolkit from Perl you can easily define hash arrays and lists that are then passed as template variables to the process method.
Example shows a Perl program similar to Example , which defines a list of friends and a hash of terms as template variables. Example is the friends. This is the output generated by Example :.
The Template Toolkit allows you to define lists and hash data structures inside templates, using syntax similar or identical if you prefer to the Perl equivalents shown earlier. The simple examples in the sections that follow should give you a flavor of how lists and hash data structures are defined and used in templates. A list variable is defined in a template using the [ List elements are accessed using the dot operator. Follow the list name with a dot and then the element number, starting at zero for the first element:.
It is also possible to access elements from the list using a variable containing an index value. Here is the same template written in a Perlish style:.
Hash items are also accessed using the dot operator. In this case, the key for the required item is specified after the dot character:. You can also access hash items using a variable that contains a key. Lists and hashes can be nested inside each other to create complex data structures:. You can access items buried deep within a nested data structure by chaining together a series of dot operations to create a compound variable :. The Template Toolkit works out which dot operators are performing hash lookups friends and name and which are performing list lookups 1 , and then automatically does the right thing to return the correct value.
This illustrates one of the key benefits of using a presentation language like the Template Toolkit for generating content, rather than a programming language such as Perl. By the time the data is presented as output in a template, it is all text anyway. You can build any kind of complex data structure. This example shows a complex, multi-levelled data structure that models an invoice. You can change by using its optional third parameter. This can take a number of different types of value.
The most common of them is a string which is assumed to be the name of a file. The output from the template is written to this file. Another option is to pass a reference to a scalar variable. In this case. This is useful if you want to post-process the output in some way. There are a few other more esoteric alternatives. For details of these see the documentation that comes with the Template Toolkit. We can do the same thing with the Template module.
In fact this method gives us even more options. In this code we set four options. If you want more than one directory then set this option to a reference to an array of directories. This can be useful if, as in this example, you want to add a header and footer to every template. Both of these values can also be set to an array reference if you want to pre- or post-process multiple templates. We use it to ensure that the invoice number always has five digits and to ensure that the prices all have two decimal points, but we also use it to ensure that the descriptions are all padded to forty characters and therefore the price column lines up correctly.
All of these considerations are about the presentation of the data, so they quite rightly belong in the template.
0コメント