#======================================================================== # # Changes # # DESCRIPTION # Revision history for the Template Toolkit version 2.00, detailing # significant changes between versions, most recent first. Some # way down the file you'll find a section detailing major changes from # version 1.* to 2.* and a list of "Gotchas!" that you might have to # look out for when upgrading between major versions. # # AUTHOR # Andy Wardley # #------------------------------------------------------------------------ # $Id: Changes,v 2.4 2000/09/12 15:32:05 abw Exp $ #======================================================================== #------------------------------------------------------------------------ # Version 2.00 beta 4 12th September 2000 #------------------------------------------------------------------------ * Added the PROCESS config option which allows a template or templates to be specified which is/are processed instead of the template passed as an argument to the Template process() method. The original template is available as the 'template' variable and can be processed by calling INCLUDE or PROCESS as [% INCLUDE $template %]. * Changed what was the CASE option to now be enabled by default, and then changed the name of the option to ANYCASE to make it more obvious as to what it did. You must now specify directive keywords (INCLUDE, FOREACH, IF, etc) in UPPER CASE only, or enable the ANYCASE option to revert to the previous behaviour of recognising keywords in any case. With the increase in reserved words in version 2, there is more chance of collision with variable names. It's a real pain not being able to have a variable called 'next', an exception called 'perl', etc., because there's a reserved word of the same name. Thus, keywords are now UPPER CASE only by default, neatly side-stepping the problem. * Changed the PERL directive so that output is generated by calling print() instead of using the final value in the block. Implemented by tying STDOUT to an output buffer based on a patch sent in by Chuck Adams. new: old: [% PERL %] [% PERL %] print "foo\n"; my $output = "foo\n"; ... ... print "bar\n"; $output .= "bar\n"; [% END %] $output; [% END %] * The IMPORT directive and magical IMPORT variable have been replaced with a general purpose virtual hash method, import(). [% hash1.import(hash2) %] # was "hash1.IMPORT = hash2" [% import(hash1) %] # was "IMPORT hash1" or "IMPORT = hash1" * Modified the Template::Filters provider to examine the FILTERS package hash reference (changed name from STD_FILTERS) each time a filter is requested rather than copying them at construction time. This allows new filters to be added on-the-fly. See t/filter.t for examples and Template::Filters for more info. * Added the 'nsort' list method which sorts items using a numerical value sort rather than an alpha sort. [% data = [ 1, 5, 10, 11 ] %] [% data.sort.join(', ') %] # 1, 10, 11, 5 [% data.nsort.join(', ') %] # 1, 5, 10, 11 * Added 'div' operator to provider integer division (e.g. 'a div b' => 'int(a / b)' and 'mod' which is identical to '%' but added for backwards compatibility with V1. * Changed the (undocumented) FORNEXT directive to NEXT and documented it. * Fixed a bug in the persistant caching mechanism in Template::Provider which was failing to write compiled template files for source templates specifed in the form [% INCLUDE foo/bar %]. Intermediate directories (like 'foo' in this example) weren't being created and the disk write was failing. Thanks to Simon Matthews for identifying this problem. * Fixed an obscure bug in the Template::Stash which was ignoring the last element in a compound variable when followed by an empty argument list. e.g. [% cgi.param() %] would be treated as [% cgi %]. Also fixed the DEBUG option so that undefined variables cause 'undef' exceptions to be raised. Thanks to Jonas Liljegren for reporting the problems. * Added the reference operator, '\' which allows a "reference" to another variable to be taken. The implementation creates a closure around the referenced variable which, when called, will return the actual variable value. It is really a form of lazy evaluation, rather than genuine reference taking, but it looks and smells almost the same. Primarily, it is useful for allowing sub-routine references to be passed to another sub-routine. This is currently undocumented because I'm not sure about the validity of adding it, but See t/refs.t for examples for now. * Changed parser to automatically unescape any escaped characters in double quoted strings except for \n and \$. This permits strings to be constructed that include tag characters. e.g. [% directive = "[\% INSERT thing %\]" %] * Fixed a bug in the use of the 'component' variable when the current component is a sub-routine rather than a Template::Document. * Added the '--define var=val' option to tpage to allow template variables to be defined from the command line. Added support to ttree for various new Template configuration options. * Added $Template::Test::PRESERVE package variable which can be set to prevent newlines in test output from being automatically mangled to literal '\n'. * Completed and corrected all knows bugs in the documentation which now weighs in at around 100 pages for the Template.pm module alone. The POD documentation should now be installed by default. The Template::Tutorial document is once again included in the distribution. #------------------------------------------------------------------------ # Version 2.00 beta 3 10th August 2000 #------------------------------------------------------------------------ * Added the WRAPPER directive to include another template, passing the enclosing block as the 'content' variable. e.g. somefile: mytable: [% WRAPPER mytable %] blah blah blah [% content %] [% END %]
This is equivalent to: [% content = BLOCK %] blah blah blah [% END %] [% INCLUDE mytable %] * Added the [% INSERT file %] directive to insert the contents of a disk file without processing any of the content. Looks for the file in the INCLUDE_PATH and honours the ABSOLUTE and RELATIVE flags. Added the insert($file) method to Template::Context which calls the new load($file) method in Template::Provider which loads the file text without compiling it. * Added the DEFAULT configuration option which allows you to specify a default template which should be used whenever a named template cannot be found. This is ignored for templates specified with absolute or relative filenames, or as references to an input filehandle or text. * Added a FORNEXT directive to step on to the next iteration of a FOREACH loop, as suggested/requested by Jo Ellen Wisnosky. I chose FORNEXT rather than simply NEXT because 'next' is a very common variable name but I'm open to better suggestions. Perhaps CASE should be set by default to prevent variable conflict? This might change. * Reorganised the Template::Filters modules and changed the calling convention for requesting filters via the fetch() method. This now expects a reference to the calling Template::Context object as the third parameter (after filter name and reference to a list of arguments). Static filter sub-routines are returned as before and the context has no effect. Dynamic filter factories (denoted by a $is_dynamic flag in the FILTER_FACTORY table) are called to create a filter sub-routine (closure) for each request. The context is now passed as the first parameter, followed by the expansion of any arguments. Filter factories should return a sub-routine or (undef, $error) on error. * Added several new filters: - 'stderr' prints the output to STDERR (i.e. for generating output in the Apache logfile, for example). e.g. [% message | stderr %] - 'file' is the equivalent of the version 1 redirect() filter which writes the output to a new file, relative to OUTPUT_PATH. Throws a 'file' exception if OUTPUT_PATH is not set. There should perhaps be some other way to disable this without relying on OUTPUT_PATH. - 'eval' evaluates the input as a template and processes it. Proposed by Simon Matthews for times when you might be returning templates fragments from a database, for example. e.g. [% dirtext | eval %] - 'evalperl' evaluate the input as Perl code, as suggested by Jonas Liligren. Requires the EVAL_PERL option to be set and will throw a 'perl' error if not (see later item). e.g. [% perlcode | evalperl %] * Fixed a bug in Template::Provider which was mangling the metadata items for the template name and modification time. The [% template.name %] and [% template.modtime %] variables now work as expected. * Added 'component' variable, similar to 'template', but which references the current template component file or block, rather than the top-level template. Of course, these may be one and the same if you're not nesting any templates. * Template::Provider now reports errors raised when re-compiling modified templates rather than ignoring them, thanks to a patch from Perrin Harkins. * Fixed Template::Context to recognise the RECURSION option once more, thanks to a patch from Rafael Kitover. * Overloaded "" stringification of Template::Exception to call as_string(), again thanks to Rafael. In a catch block you can now simply say [% error %] as well as the more explicit [% error.type %] and/or [% error.info %]. * Changed Template module (via Template::Service) to return the exception raised rather than a pre-stringified form. This allows you to test the type() and/or info() if you want, or just print it and rely on the automatic stringification mentioned above to format it as expected. Note that the top-level process($file) method returns a string rather than an exception if $file can't be found. This is a bug, or a possible "gotcha" at the very least, and should get fixed some time soon. For now, test that the error is a reference before attempting to call info() or type(). * Fixed a bug preventing literal newlines from being used in strings. Thanks to Simon Matthews for bringing it to my attention by calling my hotel room at the Perl Conference and saying "Hello? Is that the Template Toolkit Helpdesk? I have a bug to report..." :-) (I fixed it on his laptop a few minutes later - good service, eh?) * Changed Template::Parser to not compile PERL or RAWPERL blocks if EVAL_PERL is not set. Previously they were compiled but switched out at runtime. This was erroneous as rogue BEGIN { } blocks could still be executed, as noted by Randal Schwartz. Any PERL or RAWPERL blocks encountered when EVAL_PERL is disabled will now cause a 'perl' exception to be thrown. * Added a define_block($name, $block) option to Template::Context to add a definition to the local BLOCKS cache. $block can be a reference to a template sub-routine or Template::Document object or template text which is first compiled. * Any other errors thrown in a PERL blocks (assuming EVAL_PERL set) are now left unchanged. Previously, these were converted to 'perl' exceptions which prevented exceptions of other kinds being throw from within Perl code. * Applied a patch from Chris Dean to fix a bug in the list 'sort' method which was converting a single element list into a hash. The sort now does nothing unless there's > 1 elements in the list. * Changed Template::Stash set() method to append the assigned value to the end of any arguments specified, rather than prepending it to the front. e.g. The foo() method called by [% myobj.foo(x, y) = z %] now receives arguments as foo(x, y, z) instead of foo(z, x, y). * Changed Template::Base::error() to accept a reference (e.g. exception) as the first parameter. In this case, no attempt is made to concatenate (and thereby stringify) the arguments. * Added a direct stash() accessor method to Template::Context rather than relying on the slower AUTOLOAD method. * Added an iterator() method to Template::Config to require Template::Iterator and instantiate an iterator, and changed generated code for FOREACH to call this factory method. This fixes a bug with pre-compiled (i.e persistant) templates which were failing if Template::Iterator wasn't already loaded. Thanks to Doug Steinwand, Rafael Kitover and Jonas Lilegren who all identified the problem and hounded me until I fixed it. :-) * Fixed a problem with persistant templates not being reloaded due to the %INC hash. This caused 1 to be returned from require() instead of the compiled template. * Added ABSOLUTE and RELATIVE options to tpage by default. * Applied various documentation and test patches from Leon Brocard. Fixed docs to quote dotted exception types to prevent string concatenation, as noted by Randal Schwartz. Generally added a whole lot more documentation. #------------------------------------------------------------------------ # Version 2.00 beta 2 14th July 2000 #------------------------------------------------------------------------ * Added COMPILE_DIR option. This allows you to specify a separate directory in which compiled templates should be written. The COMPILE_DIR is used as a root directory and each of the INCLUDE_PATH elements is created below that point. e.g. the following options COMPILE_DIR => '/tmp/ttcache', INCLUDE_PATH => '/user/foo/bar:/usr/share/templates', would create the following cache directories: /tmp/ttcache/user/foo/bar /tmp/ttcache/usr/share/templates Templates originating from source files in the INCLUDE_PATH are thus written in their compiled form (i.e. Perl) to the relevant COMPILE_DIR directory. The COMPILE_EXT option may also be used in conjunction with COMPILE_DIR to append a filename extension to all compiled files. * Fixed memory leaks caused by the huge circular reference that is the Template::Provider's linked list of cache slots. Added a DESTROY method which walks the list and explicitly breaks the chains (i.e. the NEXT/PREV links), thus allowing the compiled Template::Document objects to be correctly destroyed and their memory repooled. Thanks to Perrin Harkins for spotting the problem. * Added a work-around in Template::Stash _dotop() to the problem of the CGI module denying membership of the UNIVERSAL class on subsequent calls to UNIVERSAL::isa($cgi, 'UNIVERSAL'). It works correctly the first time, but returns false for all subsequent calls. Changed this generic "is-an-object" test to UNIVERSAL::can($cgi, 'can') on the suggestion of Drew Taylor who identified the problem. * Added t/macro.t to test MACRO directive, t/compile4.t and t/compile5.t to test the COMPILE_DIR option. * More complete documentation, but not yet fully complete. #------------------------------------------------------------------------ # Version 2.00 beta 1 10th July 2000 #------------------------------------------------------------------------ * Template::Context include()/process() now works with raw CODE refs. * Template.pm now prefixes OUTPUT with the OUTPUT_PATH when OUTPUT is a file name. * Cleaned up Template::Iterator. Now derived from Template::Base. Removed ACTION and ORDER now that they are supported as list pseudo methods in the Stash LIST_OPS. * Fixed bug in Provider preventing updated files from being automatically reloaded. Thanks to Perrin Harkins who provided the patch. * Fixed bug in Template::Plugin::Datafile which was preventing a comment from being placed on the first line of the file. * Fixed bug in parse grammer preventing commas in a META list * Added cache persistance by writing real Perl to file (rather than the previous Data::Dumper dump of the opcode tree). Had to re-organise a bunch of code around the parser/provider/document. Activated by COMPILE_EXT configuration item. * Added a work-around in Template::Stash to the problem of CGI disclaiming membership of the UNIVERSAL class after the first method call. * Added AUTO_RESET option which is enabled by default. Disable this (AUTO_RESET => 0) for block persistance across service invocations. * Fixed \@ quoting (and others) in Directive thanks to Perrin Harkins who reported the bug and Chuck Adams who provided a patch. * Added Date plugin and test, as provided by Thierry-Michel Barral. * Integrated changes to Template::Test from version 1.07 and beyond. Now supports -- process -- option in expect, mainly for use of t/date.t et al. * Integrated new upper and lower filters from 1.08, and '|' alias for FILTER from 1.07. * Added new directive.t test to test chomping and comments. * BLOCKS can now be defined as template text which gets automatically compiled into a Template::Document object. * Integrated XML plugins and tests from version 1.07 * Fixed TRIM option to work with all BLOCKs and templates. Moved TRIMing operation into context process() and include() methods. Also changed service to call $context->process($template) rather than call the sub/ doc itself, thus ensuring that the output can get TRIMmed. * Updated Template::Plugin.pm * Added '--define' option to ttree. * Integrated various plugins and filters from v1.07 * Moved Template::Utils::output into Template.pm?) and got rid of Template::Utils altogether. * Fixed bug in Context filter() provider method which wasn't caching filters with args. * [% CASE DEFAULT %] is now an alias for [% CASE %] (the default case), in consistency with [% CATCH DEFAULT %] / [% CATCH %] #------------------------------------------------------------------------ # Version 2.00 alpha 1 #------------------------------------------------------------------------ * first public alpha release of Version 2.00 #======================================================================== # VERSION 2.00 #------------------------------------------------------------------------ # The following list outlines the major differences between version 1.* # and version 2.00 of the Template Toolkit. #======================================================================== New Language Features --------------------- * New SWITCH / CASE statement. SWITCH takes an expression, CASE takes a value or list of values to match. CASE may also be left blank or written as [% CASE default %] to specify a default match. Only one CASE matches, there is no drop-through between CASE statements. [% SWITCH myvar %] [% CASE value1 %] ... [% CASE [ value2 value3 ] %] # multiple values to match ... [% CASE myhash.keys %] # ditto ... [% CASE %] # default, or [% CASE default %] ... [% END %] * New TRY / CATCH / FINAL construct for fully functional, nested exception handling. The block following the TRY is executed and output if no exceptions are throw. Otherwise, the relevant CATCH block is executed. CATCH types are hierarchical (e.g 'foo' catches 'foo.bar') or the CATCH type may be left blank or specified as [% CATCH default %] to provide a default handler. The contents of a FINAL block, if specified, will be processed last of all, regardless of the result (except an uncaught exception which is throw upwards to any enclosing TRY block). [% TRY %] ...blah...blah... [% CALL somecode %] # may throw an exception ...etc... [% INCLUDE someblock %] # may have a [% THROW ... %] directive ...and so on... [% CATCH file %] # catch system-generated 'file' exception ... [% CATCH DBI %] # catch 'DBI' or 'DBI.*' ... [% CATCH %] # catch anything else ... [% FINAL %] # optional All done! [% END %] * New CLEAR directive to clear the current output buffer. This is typically used in a CATCH block to clear the output of a failed TRY block. Any output generated in a TRY block up to the point that an exception was thrown will be output by default. The [% CLEAR %] directive in a catch block clears this output from the TRY block. [% TRY %] blah blah blah, this is the current output block [% THROW some.error 'Danger Will Robinson!' %] not reached... [% CATCH %] [% # at this point, the output block contains the 'blah blah...' line # up to the point where the THROW occured, but we don't want it CLEAR %] Here we can add some more text if we want... [% END %] In general, the CLEAR directive clears the current output from the template or enclosing block. * New META directive allowing you to define metadata items for your templates. These are attached to the compiled template and wrapped up as a Template::Document object. The 'template' variable is a reference to the current parent document and metadata items may be accessed directly. Of particular note is the fact that the 'template' variable is correctly defined for all PRE_PROCESS and POST_PROCESS headers. Thus, your headers and footers can access items from the main template (e.g. title, author, section, keywords, flags, etc) and display them or act accordingly. mytemplate: [% META title = 'This is a Test' author = 'Andy Wardley' copyright = "2000, Andy Wardley" %]

[% template.title %]

blah blah header: (a PRE_PROCESS template) [% template.title %] footer: (a POST_PROCESS template)
© Copyright [% template.copyright or '2000, MyCompany' %] * New RAWPERL ... END block directive allows you to write raw Perl code which is integrated intact and unsullied into the destination template sub-routine. The existing PERL ... END directive continues to be supported, offering runtime evaluation of a block which may contain other template directives, etc, which are first evaluated (e.g. PERL...END processes the block and filters the output into Perl evaluation at runtime). * New INSERT directive which inserts the contents of a file without processing it. * New WRAPPER directive which processes the following block into the 'content' variable and then INCLUDEs the named file. [% WRAPPER table %] blah blah blah [% END %] [% BLOCK table %] [% content %]
[% END %] * Comments now only extend to the end of the current line. [% # this is a comment a = 10 # so is this b = 20 %] Placing the '#' character immediately inside the directive will comment out the entire directive [%# entire directive is ignored %] * The TAGS directive can now be used to switch tag styles by name. Several new tag styles are defined (e.g. html, asp, php, mason). [% TAGS html %] * The output from any directive or block can now be captured and assigned to a variable. [% htext = INCLUDE header %] [% btext = BLOCK %] blah blah [% x %] [% y %] [% z %] [% END %] # you can even assign the output of loops, conditions, etc. [% numbers = FOREACH n = [2, 3, 5, 7, 11, 13] %] blah blah [% n %] [% END %] * The handling of complex expressions has been improved, permitting basic directives to contain logical shortcut operators, etc. All binary operators now have the same precedence rules as Perl. [% foo or bar %] # GET foo, or bar if foo is false (0/undef) [% CALL func1 and func2 %] # func2 only called if func1 returns true [% name = user.id or cgi.param('id') %]. * A new "x ? y : z" operation is provided as a shorthand for "if x then y else z" [% foo = bar ? baz : qux %] * A leading '$' on a variable is now used to indicate pre-interpolation of that element. This simplifies the syntax and makes it consistent with double-quoted string interpolation and text block interpolation via the INTERPOLATE flag. If you've been relying on the version 1 "feature" that ignores the leading '$' then you'll need to change your templates to remove the '$' characters (except where you really want them) or set the V1DOLLAR flag to 1 to revert to the version 1 behaviour. See the 'Gotchas' section below for more details. # version 1 [% hash.${key} %] [% hash.${complex.key} %] # version 2 [% hash.$key %] [% hash.${complex.key} %] * Various new pseudo-methods have been added for inspecting and manipulating data. The full list now looks something like this: [% var.defined %] # variable is defined [% var.length %] # length of string [% var.split(delimiter, limit) %] # split string as Perl does [% hash.keys %] # return list of hash keys [% hash.values %] # ditto hash values [% list.size %] # number of items in list [% list.max %] # last item number (size - 1) [% list.first %] # first item [% list.last %] # last item [% list.reverse %] # list in reverse order [% list.sort(field) %] # list in sorted order [% list.join(joint) %] # join items into single string Templates Compiled to Perl Code ------------------------------- Templates are now compiled to Perl code, with credit and respect due to Doug Steinwand for providing an implementation around which the new parser was built. This brings a number of important benefits: * Speed and Memory Efficiency Version 1 used a list of opcodes to represent directives and lower-level operations. These were evaluated by the hideously contrived, and darkly sinister Template::Context::_evaluate() method. In version 2, all templates are parsed and rebuilt as Perl code. This is then evaluated and stored as a reference to a Perl sub-routine which can then be executed and re-executed significantly faster and with far less memory overhead. * Persistance. Once a template has been compiled to Perl code it can be saved to disk as a "compiled template" by defining the COMPILE_EXT option. This allows you to specify a filename extension (e.g. '.ttc') which is added to the template filename and used to create a new file containg the Perl code. Next time you use the template, even if you've shut down your program/server/computer in the mean time, the compiled template is there in a file as Perl code and is simply require()d and executed. It all happens significantly faster because there's no Template::Parser to run. In fact, if all your templates are "compiled" on disk then the Template::Parser and Template::Grammar modules won't even be loaded, further reducing startup time and memory consumption (the grammar file, in particular is rather large). The Template::Provider module handles the loading, caching and persistance of templates, and will examine file timestamps and re-compiled modified templates as required. * Flexibility. Because "compiled templates" are now nothing more than Perl sub-routines, you can use anyone or anything to generate them and run them all under the same roof. Different parser back-ends can generate Perl code optimised for speed or functionality, for example. Or different parsers can compile different template languages (PHP, ASP, Mason, roll-your-own, etc.) and run them alongside regular templates. Or if you don't trust a parser, you can even write your own Perl code and have your templates execute as fast as the code you can write. Configuration Options --------------------- * Template blocks may be pre-defined using the new BLOCKS option. These may be specified as template text or as references to sub-routines or Template::Document objects. my $template = Template->new({ BLOCKS => { header => '[% title %]', footer => '', funky => sub { blah_blah($blah); return $some_text }, } }); * Automatic error handling can be provided with the ERROR option. This allows you to specify a single template or hash array of templates which should be used in the case of an uncaught exception being raised in the a template. In other words, if something in one of your templates throws a 'dbi' error then you can define an ERROR template to catch this. The original template output is discarded and the ERROR template processed in its place. PRE_PROCESS and POST_PROCESS templates (e.g. header and footers) are left intact. This provides a particularly useful high-level error handling abstraction where you simply create templates to handle particular exceptions and provide the mapping through the ERROR hash. my $template = Template->new({ ERROR => { dbi => 'error/database.html', # DBI error 'user.pwd' => 'error/badpasswd.html', # invalid user password user => 'user/index.html', # general 'user' handler default => 'error/error.html', # default error template } }); * The INCLUDE_PATH is now fully dynamic and can be changed at any time. The new Template::Provider which manages the loading of template files will correctly adapt to chahges in the INCLUDE_PATH and act accordingly. * The LOAD_TEMPLATES option allows you to specify a list of one or more Template::Provider object which will take responsibility for loading templates. Each provider can have it's own INCLUDE_PATH, caching options (e.g CACHE_SIZE) and so on. You can sub-class the Template::Provider module to allow templates to be loaded from a database, for example, and then define your new provider in the LOAD_TEMPLATES list. The providers are queried in order as a "Chain of Responsiblity". Each may return a compiled template, raise an error, or decline to serve the template and pass control onto the next provider in line. * The CACHE_SIZE option defines a maximum number of templates that will be cached by the provider. It is undefined by default, causing all templates to be cached. A value of 0 disables caching altogether while a positive integer defines a maximum limit. The cache (now built into Template::Provider) is much smarter and will automatically reload and compile modified source templates. * The Template::Provider cache can write compiled templates (e.g. Perl code) to disk to create a persistant cache. The COMPILE_EXT may be used to specify a filename extension (e.g. '.ttc') which is used to create compiled template files. These compiled template files can then be reloaded on subsequent invocations using via Perl's require() (which is about as fast as it can get). The Template::Parser and Template::Grammar modules are loaded on demand, so if all templates have been pre-compiled then the modules don't get loaded at all. This is a big win, given that Template::Grammar is the biggy. * The ABSOLUTE and RELATIVE options are now used to enable the loading of template files (via INCLUDE or PROCESS) that are specifies with absolute (e.g. /tmp/somefile) or relative (e.g. ../tmp/another) filenames. Both are disabled by default. * The LOAD_PLUGINS option is similar to LOAD_TEMPLATES but allows you to specify one or more plugin providers. These take responsibility for loading and instantiating plugins. The Template::Plugins module is the default provider and multiplexes requests out to other Template::Plugin::* plugin modules. Loading of plugins has been simplified and improved in general The PLUGINS option can be used to map plugin names to specific modules and PLUGIN_BASE can map plugins into particular namespaces. The LOAD_PERL option can be used to load (almost) any regular Perl module and use it as a plugin. * The LOAD_FILTERS option is similar to LOAD_TEMPLATES and LOAD_PLUGINS, allowing one or more custom providers to be specified for providing filters. The Template::Filters module is the default provider here. * The TOLERANT option can be used to tailor the behaviour of providers (e.g. Template::Provider, Template::Plugins, Template::Filters) when they encounter an error. By default, providers are not TOLERANT (0) and will report all failures as errors. When TOLERANT is set to 1, they will ignore errors and return STATUS_DECLINED to give the next provider a chance to deliver a valid resource. * The INTERPOLATE option is now automatically disabled within PERL and RAWPERL blocks to prevent Perl $variables from being interpreted as template variables. # INTERPOLATE = 1 This $var will get interpolated... [% PERL %] # but these won't my $foo = 'some value'; my $bar = 'another value'; # etc... [% END %] now we're interpolating variables again, like $var * Added the TRIM option to automatically removed leading and trailing whitespace from the output of templates and BLOCKs. Other Enhancements and Internal Features ---------------------------------------- * Templates (i.e. sub-routines) now return their generated output, rather than sending it to $context->output(). This speeds things up and makes the code simpler, as well as allowing greater flexibility in how template sub-routines can work. * Exceptions are now raised via Perl's die() and caught by an enclosing eval { } block. Again, this simplifies the code generated and improves runtime efficiency. The [% RETURN %] and [% STOP %] directives are now implemented as special case exceptions which are caught in the appropriate place and handled accordingly. * Local named BLOCK definitions are better behaved and don't permanently mask any real files. BLOCK definitions remain local to the template in which they're defined, although they can be accessed from templates INCLUDEd or PROCESSed from within. The PROCESS directive will export defined BLOCKs to the caller (as with variables) whereas INCLUDE will keep them "private". * The Template::Stash object now encapsulates all the magical variable resolution code. Both simple and compound variables can be accessed or updated using the get() and set() methods, with all variable binding magic happening automatically. * The Template::Context object is now greatly simplified. This acts as a general interface to the Template Toolkit functionality, being a collection of the various other modules that actually implement the functionality (e.g. Template::Stash, Template::Provider, Template::Document, Template::Plugins, etc.) * The Template::Provider object provides a general facility for retrieving templates from disk (or other source), and if necessary compiling via a call to a Template::Parser helper object. Multiple Template::Provider objects may be chained together, each with their own caching options, and so on. * The Template::Parser object now compiles template text into Perl code and then evaluates it into a sub-routine reference using Perl's eval(). This is then wrapped up into a Template::Document object, including any metadata items and/or additional named BLOCKs defined in the input template. * The Template::Document object is a thin wrapper around a compiled template sub-routine. It provides a process() method for processing the template and a blocks() method for returning a reference to the hash array of any additional named BLOCKs defined in the original template text. An AUTOLOAD method returns values of metadata items, allowing a Template::Document reference to be used as the 'template' variable. * The Template::Service module provides a high-level service for processing templates, allowing PRE_PROCESS and POST_PROCESS templates to be specified along with an ERROR handling hash. * The Template::Base module defines a common base class for many of the toolkit modules. It implements shared functionality such as a constructor, error reporting and handling, etc. Modules are now much easier to sub-class, all using separate new() and _init() methods. * The Template::Config module provides methods for loading and instantiating different Template Toolkit modules. Using this factory-based approach makes it far easier to change the default object class for a specific part of the toolkit. e.g. use Template; use Template::Config; $Template::Config::PARSER = 'MyOrg::Template::MyParser'; # $tt object will create and use a MyOrg::Template::MyParser # object as PARSER my $tt = Template->new({ ... }) * The Template module remains, as it ever was, a simple front-end to the Template Toolkit. This creates a single Template::Service to which it delegates control for processing templates. Output is returned according to the OUTPUT options specified for the module and/or any output option passed explicitly to the process() method. Plugins and Filters ------------------- * Added the 'upper' and 'lower' filters for case folding text. * Added the Date plugin. Tools and Tests --------------- * Added the --define var=val option to ttree. * Added '-- use name --' to Template::Test to switch between multiple Template objects specified as a list reference as the second arg to test_expect() * Totally updated the test suite. Gotchas ------- Things that have changed between version 1 and 2 that might catch you out. * Bare CATCH blocks are no longer permitted and must be explicitly scoped with a matching TRY. In most cases, this simply means adding a [% TRY %] to the start of any templates that define CATCH blocks, and ensuring that the CATCH blocks are moved to the end of the file (or relevant place). # version 1 - no longer supported blah blah blah...some error occurs [% CATCH some_kind_of_error %] handler template... [% END %] # version 2 [% TRY %] blah blah blah...some error occurs... [% CATCH some_kind_of_error %] handler template... [% END %] Also be aware that this may change the expected output in case of errors. By default, all output in the TRY block up to the point of error will be returned, with the relevant catch block, and then and further template output appended. You can use [% CLEAR %] within a CATCH block to clear the output from the TRY block, if you prefer. TRY blocks can be nested indefinately. * The ERROR directive is no longer supported. It was very ill-defined anyway and serves no purpose that can't be acheived by defining custom filters, error handlers bound to template variables, or whatever. I haven't implemented any special error or logging facilities, other than the general purpose exception handling, but welcome any thoughts on what or if anything else is needed. * The ERROR option is also different. It could previously be used to specify an error handling sub-routine, but is no longer required (see previous point). The ERROR option in version 2 is used to define a map of error types to template names for automatic redirection for error handling. * The current exception caught in a catch block is now aliased to the variable 'error' rather than 'e'. This is much more logical, IMHO, and was only prevented previously by 'error' being a reserved word. Note that 'e' is still defined, in addition to 'error'. This may be deprecated at some point in the future. * The use of a leading '$' on variables is no longer optional, and should only be used to explicitly to indicate interpolatation of a variable name. Most of the time you *don't* want to do this, so leave the '$' off. This represent a slight shift away from the (optional) Perlness of the language, but I think it's a necessary step to improve the clarity and consistency of the language. As previously discussed on the mailing list, in interpolated text (i.e. a "double quoted" string or regular template text with INTERPOLATE set), both '$foo' or '${foo}' are interpolated as the value of the variable 'foo'. This is good because it is a de-facto standard, consistent with Perl, shell, etc. But inside a directive, [% $foo %] and [% ${foo} %] mean different things, the first being equivalent to [% foo %] or [% GET foo %] (the leading '$' is ignored) but the second actually fetching a variable whose name is stored in the variable 'foo'. In other words, '${foo}' interpolates to the value of foo ('bar', say) and then this is used as the parameter to GET (which itself is optional). Thus, in this case, [% ${foo} %] is [% GET ${foo} %] is [% GET bar %]. This makes more sense if you look at the common example of accesing an entry from a hash array using the value of an variable as the key (e.g. $hash->{ $key }). In version 1, the leading '$' on variables is ignored, meaning that the following are NOT identical. # version 1 [% hash.$key %] # ERROR - '$' ignored => [% hash.key %] [% hash.${key} %] # OK - '$key' is interpolated first It gets more confusing if you excercise your right to add optional leading '$'s in other places (which is one reason why I've always suggested against their use). # version 1 - same as above [% $hash.$key %] [% $hash.${key} %] In particular, that last example should demonstrate the inconsistency. Unlike interpolated text, '$...' and '${...}' are not treated the same and '$hash' is not interpolate while '${key}' is. The only consistent solution I can see to this is to make both '$xxx' and '${xxx}' indicate interpolation in all cases, so that's what I've done. In version 2, the syntax becomes a lot clearer and aligns more closely to a markup language than a programming language. I think this is a Good Thing, but let me know what you think... Here's the Version 2 summary, assuming INTERPOLATE is set. # version 2 my name is $name my name is $user.name my name is ${user.name} [% GET name %] [% name %] [% GET user.name %] [% user.name %] [% GET people.fred %] [% people.fred %] [% GET people.$name %] [% people.$name %] [% GET people.${user.name} %] [% people.${user.name} %] [% INCLUDE header title = "Home Page for $name" %] [% INCLUDE header title = "Home Page for $user.name" %] [% INCLUDE header title = "Home Page for ${user.name}" %] * Changed default TAG_STYLE to only recognise [% ... %] and not the MetaText compatability %% ... %% style. Set TAG_STYLE => 'template1' to accept both, or 'metatext' for just %% ... %% * Changed how error/return values should be returned from user code. All errors should be thrown via one of the following: die $error_msg; die Template::Exception->new($type, $info); $context->throw($msg); $context->throw($type, $info); $context->throw($exception); * USERDIR and USERBLOCK are not supported (they were experimental and undocumented, anyway) * $Template::Directive::While::MAXITER is now $Template::Directive::WHILE_MAX and may change again. * into() filter is now obsolete. You can now simply assign the output of another directive or block to a variable. [% x = INCLUDE foo %] [% y = BLOCK %] blah blah blah [% END %] * The CASE option has been removed and replaced with the ANYCASE option which is the logical opposite. Directive keywords should now be UPPER CASE by default and the ANYCASE option can be enabled to revert to the previous behaviour of accept keywords in any case. * The IMPORT directive and magical variable have been removed and replaced by a general purpose virtual hash method, import(). [% IMPORT myhash %] should now be written [% import(myhash) %] and [% myhash.IMPORT = another.hash %] should be written as [% myhash.import(another.hash) %]