Perl template toolkit increment variable
Thus, the previous example could have been written:. In Perl 5, the. This can be particularly useful in common template components to ensure that some sensible default is provided for otherwise undefined variables. If a true value is provided for variables with DEFAULT values, the provided value will be used; otherwise, the default value will be used.
Variables are for storing little bits of data. Templates are for writing larger chunks of content. As with variables, it is often useful to be able to reuse the contents of a template.
For example, the output of a template will often actually be composed of the output of a number of lower-level templates.
These lower-level templates can be reused in other templates. This is very similar to the modular approach to writing programs that encourages code reuse. The Template Toolkit provides a number of directives for manipulating templates. The first three of these all work in a very similar way.
The basic syntax for these directives looks like this:. With all of these directives, the results of processing the template are included in the output in place of the directive. It is a block directive and it allows you to define a template that is wrapped around the block of content.
The content of the block is made available to the wrapper template in a special variable called content. No attempt to parse or process the file is made. The contents, possibly including any embedded template directives, are inserted intact. Absolute i. Both of these options are disabled by default. For convenience, the filename does not need to be quoted as long as it contains only alphanumeric characters, underscores, dots, or forward slashes.
Names containing any other characters should be quoted. All files should be unquoted names or quoted strings. Any variables should be interpolated into double-quoted strings. If a BLOCK of the specified name is defined in the same file or in a file from which the current template has been called i. Any template directives embedded within the file will be processed accordingly.
All variables currently defined will be visible and accessible from within the included template. Local variable definitions may be specified after the template name, temporarily masking any existing variables. Insignificant whitespace is ignored within directives, so you can add variable definitions on the same line, on the next line, or split across several lines with comments interspersed, if you prefer.
Any changes made within the included template will not affect variables in the including template. The localization of the stash that is, the process by which variables are copied before an INCLUDE to prevent being overwritten is only skin-deep.
The top-level variable namespace hash is copied, but no attempt is made to perform a deep-copy of other structures hashes, arrays, objects, etc. Therefore, a foo variable referencing a hash will be copied to create a new foo variable that points to the same hash array.
Thus, if you update compound variables e. This behavior can be a little unpredictable and may well be improved upon in a future version. Otherwise, you might prefer to steer clear and always pass simple undotted variables as parameters to INCLUDE and other similar directives.
The variable stash is localized once and then the templates specified are processed in order, all within that same variable context. This might be what you want, of course, but then again, it might not. Any changes made to variables within the included template will be visible in the including template. For example, this code:. As such, the following code:. For example:. It encloses a block to a matching END directive, which is first processed to generate some output. The specification order indicates outermost to innermost wrapper templates.
For example, given the following template block definitions:. END construct can be used to avoid this. A BLOCK definition can be used before it is defined, as long as the definition resides in the same file.
The block definition itself does not generate any output. Like a named block, an anonymous block can contain any other template directives that are processed when the block is defined. The output generated by the block is then assigned to the variable julius. The enclosing block is processed each time the macro is called. It is very common to want to repeat parts of a template. You might want to produce similar output for every item in a list, or you might want to repeat a piece of content a set number of times.
Use FOREACH in cases where you know the size of the data set over which you are iterating, or in cases where you need access to loop metadata, such as the next or previous element, the index of the iteration, or the size of the data set. WHILE is useful for performing an action until a condition is true, for looping over a very large data set, or when termination of the loop depends on a condition external to the data set. Both directives are discussed in the sections that follow.
The basic syntax is:. In this example, numbers is an array of five elements, the numbers 1 through 5. The elements of the array can be any kind of complex data:. The beatle variable is aliased to each hash in the fabfour list, and through it we can access the various elements:. When the FOREACH directive is used without specifying a target variable, any iterated values that are hash references will be automatically imported:.
This particular usage creates a localized variable context to prevent the imported hash keys from overwriting any existing variables. The imported definitions and any other variables defined in such a FOREACH loop will be lost at the end of the loop, when the previous context and variable values are restored.
To iterate over the keys of a hash, use the keys virtual method on the hash:. The underlying implementation of the FOREACH directive involves the creation of a special object called an iterator , which maintains metadata about the data set being processed.
The iterator defines several useful methods that return information about the current loop:. Returns the size of the data set, or returns undef if the dataset has not been defined. Returns the maximum index number i. Returns the number of the current item, in the range 0 to max. Returns a Boolean value to indicate whether the iterator is currently on the first iteration of the set.
Returns a Boolean value to indicate whether the iterator is currently on the last iteration of the set. Returns the previous item in the data set, or returns undef if the iterator is on the first item. Returns the next item in the data set, or undef if the iterator is on the last item. An iterator plugin is available that enables you to control how an iterator is created; if an iterator object is passed to a FOREACH loop, it is used as is a new iterator is not created. Nested loops will work as expected, with the loop variable correctly referencing the innermost loop and being restored to any previous value i.
The iterator plugin can also be used to explicitly create an iterator object. This can be useful within nested loops where you need to keep a reference to the outer iterator within the inner loop.
The iterator plugin effectively allows you to create an iterator by a name other than loop. See the manpage for Template::Plugin::Iterator for further details. WHILE loops are used to repeatedly process a template block. The test condition follows the same rules as those for IF blocks. The Template Toolkit uses a fail-safe counter to limit the number of loop iterations to prevent runaway loops that never terminate. If the loop exceeds 1, iterations, an undef exception will be thrown, reporting the error:.
The LAST directive can be used to prematurely exit the loop. See the section titled Section 4. Perhaps your web site should be orange on certain days of the week, or maybe negative numbers should be displayed in red. The Template Toolkit has a number of conditional directives that allow your template to make decisions about what path to take. A conditional controls execution of a block of code, based on the value of a variable. After the optional third output argument can come an optional reference to a hash or a list of name, value pairs providing further options for the output.
The only option currently supported is binmode which, when set to any true value will ensure that files created but not any existing file handles passed will be set to binary mode. Alternately, the binmode argument can specify a particular IO layer such as :utf8. The process method returns 1 on success or undef on error. The error message generated in the latter case can be retrieved by calling the error method. Thus, the following are equivalent.
Errors are represented in the Template Toolkit by objects of the Template::Exception class. If the process method returns a false value then the error method can be called to return an object of this class.
The type and info methods can called on the object to retrieve the error type and information string, respectively. This method is also overloaded onto the stringification operator allowing the object reference itself to be printed to return the formatted error string. The Template module delegates most of the effort of processing templates to an underlying Template::Service object.
This method returns a reference to that object. The Template::Service module uses a core Template::Context object for runtime processing of templates. This method is a simple wrapper around the Template::Context method of the same name. It returns a compiled template for the source provided as an argument. The following list gives a short summary of each Template Toolkit configuration option.
See Template::Manual::Config for full details. Root of directory in which compiled template files should be written default: undef - don't compile. Flag to indicate regular Perl modules should be loaded if a named plugin can't be found default: 0. The delimiter can be surrounded by optional whitespace which is removed from the values. The first row must contain the names of the data items and any blank lines or comment lines which start with a character are ignored.
The remaining problem is that this prints out all of the letters in a continuous piece of text, but actually we want each letter on a separate page. We can achieve this by inserting a form-feed character 0x0C at the end of each page like this:. These prevent an extra form-feed being output after the last letter. A printer will automatically perform a form feed at the end a print job, so if our output contains one as well there will be two form-feeds in the job and an extra blank sheet of paper will be used.
We can prevent that using the code shown. This allows your template to access data stored in most kinds of database. Assuming that our data is stored in a table called debtors in a MySQL database called accounts, we can change our template to look like this:. The new code simple enough to follow.
We load the DBI plugin, passing it the various parameters required to connect to the database. We then run an SQL query against the database. This returns an iterator object that we can use in a FOREACH directive in exactly the same way that we used the iterator that the Datafile plugin created. Each value returned by the iterator is object which contains data items for each of the columns selected from the database.
The names of these data items are given by the column names in the SQL statement. We can use the Date plugin to fix that. We can load the Date plugin with a directive like this:. Here we have given the Date plugin a format string. Having seeded the plugin with that format, any dates that are passed to the date. If you want to override the default format at any time, you can pass a new format definition as the second argument to the date. One small problem with the Date plugin is that it is a little fussy about the format of the date.
Two things to notice here. What if our data is stored as an XML document? XPath plugin to access data within a document. The template first creates a XML. XPath plugin in the USE directive.
0コメント