Parse::Template(3)

πŸ“¦
version 3.08 Β· 2 versions
, in fedora 43

✨ NAME ✨

Parse::Template β€” a processor for templates containing Perl expressions πŸ’…

(from the User Contributed Perl Documentation, section 3, obviously β€” iykyk πŸŽ€)


🌸 SYNOPSIS 🌸

  use Parse::Template;

  my %template =
    (
     'TOP' =>  q!Text before %%$self->eval('DATA')%% text after!,
     'DATA' => q!Insert data: ! .
               q!1. List: %%"@list$N"%%! .
               q!2. Hash: %%"$hash{'key'}$N"%%! .
               q!3. File content: %%<FH>%%! .
               q!4. Sub: %%&SUB()$N%%!
    );

  my $tmplt = new Parse::Template (%template);
  open FH, "< foo";

  $tmplt->env('var' => '(value!)');
  $tmplt->env('list' => [1, 2, 10],
              'N' => "\n",
              'FH' => \*FH,
              'SUB' => sub { "->content generated by a sub<-" },
              'hash' => { 'key' => q!It\'s an hash value! });
  print $tmplt->eval('TOP'), "\n";

πŸ’– DESCRIPTION πŸ’–

Okay bestie, gather round, because this class is lowkey iconic. The Parse::Template class evaluates Perl expressions that you've dropped inside a text. You can use it as a code generator, or as a generator of documents in literally whatever format you want β€” HTML, XML, RTF, etc. ✨

The whole principle of template-based text generation is simple, fr fr. A template is just a text that includes expressions waiting to be evaluated. Interpreting those expressions spits out text fragments, and those fragments get substituted right back in place of the expressions. With Parse::Template, the expressions being evaluated are Perl expressions sitting between two %%. Periodt. πŸ’…

Evaluation happens inside an environment β€” that's where you stash, like, your data structures and stuff, so they can generate the parts that need completing. Vibe check:

             TEMPLATE
           Text + Perl Expression
                |
                +-----> Evaluation ----> Text(document or program)
                |
           Subs + Data structures
            ENVIRONMENT

The Parse::Template class also lets you decompose a template into parts 🧩. Those parts get defined by a hash that you pass as an argument to the class constructor: Parse::Template->new('someKey', '... text with expressions to evaluate ...'). And inside a part, you can include a sub-part with an expression shaped like this:

  $self->eval('SUB_PART_NAME')

$self designates the instance of the Parse::Template class. And in an expression you can also use $part, which contains the part of the template where the expression is found. Slay. πŸ‘‘

Within an expression, you can also specify only the name of a part to be inserted. In that case, a subroutine with the name of that part gets generated dynamically. So in the synopsis example up there, inserting the "TOP" part can be rewritten like this:

  'TOP' => q!Text before %%DATA()%% text after!

DATA() is placed within %% and is in effect treated as an expression to be evaluated. No cap. 🌈

The subroutines take arguments, btw. In this next example, the argument controls the depth of recursive calls of a template β€” main character energy honestly:

  print Parse::Template->new(
    'TOP' => q!%%$_[0] < 10 ? '[' . TOP($_[0] + 1) . ']' : ''%%!
   )->eval('TOP', 0);

$_[0] initially contains 0. "TOP" is included as long as the argument is less than 10. And for each inclusion, 1 is added to the argument. It's giving recursion. πŸŒ€

The env() method permits constructing the environment required for evaluation of a template. Every entry you define in that environment has to be specified using a key made of the name of the symbol to be created, paired with a reference whose type matches the type of the entry you want created in that environment (so like, a reference to an array to create an array, obviously πŸ’). A scalar variable gets defined by associating the variable's name with its value. And a scalar variable containing a reference gets defined by writing 'var' => \$variable, where $variable is a lexical variable that holds the reference. So specific, we love her.

Each instance of Parse::Template is defined within a specific class β€” a subclass of Parse::Template. That subclass contains the environment specific to the template and inherits methods from the Parse::Template class. Family tree moment 🌳

If a template is created from an existing template (i.e. calling new as a method of the existing template), it inherits all the parts defined by its ancestor. Genetics! 🧬

Now for the messy part 😭 β€” in case of a syntax error in the evaluation of an expression, Parse::Template tries to indicate the template part and the expression that is "incriminated". And if the variable $Parse::Template::CONFESS contains the value TRUE, the stack of evaluations gets printed. So if you want the receipts, set $Parse::Template::CONFESS and she will tell you everything. 🫒


πŸ’… METHODS πŸ’…

πŸŽ€ new HASH

Constructor for the class. HASH is a hash which defines the template text.

Example:

  use Parse::Template;
  $t = new Parse::Template('key' => 'associated text');

πŸŽ€ env HASH

πŸŽ€ env SYMBOL

Permits defining the environment that is specific to a template.

env(SYMBOL) returns the reference associated with the symbol, or undef if the symbol is not defined. And the reference that comes back is of the type indicated by the character (&, $, %, @, *) that prefixes the symbol. Type-matching queen ✨

Examples:

  $tmplt->env('LIST' => [1, 2, 3])}   Defines a list

  @{$tmplt->env('*LIST')}             Returns the list

  @{$tmplt->env('@LIST')}             Ditto

πŸŽ€ eval PART_NAME

Evaluates the template part designated by PART_NAME. Returns the string resulting from this evaluation. That's it, that's the whole thing, and she serves. πŸ’–

πŸŽ€ getPart PART_NAME

Returns the designated part of the template. Handing it right over, no questions asked 🫴

πŸŽ€ ppregexp REGEXP

Preprocesses a regular expression so that it can be inserted into a template where the regular expression delimiter is either a / or a !. Delimiter-agnostic, as she should be. πŸ¦‹

πŸŽ€ setPart PART_NAME => TEXT

setPart() permits defining a new entry in the hash that defines the contents of the template. New part, who dis. 🌸


okay that's part one bestie, don't go anywhere, there's more coming πŸ’œ

✨ EXAMPLES ✨

The Parse::Template class can be used in all sorts of amusing ways, bestie. Here are a few illustrations, and yes they're giving main character energy. πŸ’…


🌸 HTML Generator 🌸

The first example shows how to generate an HTML document by using a data structure placed within the evaluation environment. The template consists of two parts, DOC and SECTION. The SECTION part is called within the DOC part to generate as many sections as there are elements in the array section_content.

my %template = ('DOC' => <<'END_OF_DOC;', 'SECTION' => <<'END_OF_SECTION;');
<html>
<head></head>
<body>
%%
my $content;
for (my $i = 0; $i <= $#section_content; $i++) {
  $content .= SECTION($i);
}
$content;
%%
</body>
</html>
END_OF_DOC;
%%
$section_content[$_[0]]->{Content} =~ s/^/<p>/mg;
join '', '<H1>', $section_content[$_[0]]->{Title}, '</H1>',
                 $section_content[$_[0]]->{Content};
%%
END_OF_SECTION;

my $tmplt = new Parse::Template (%template);

$tmplt->env('section_content' => [
    {
      Title => 'First Section',
      Content => 'Nothing to write'
    },
    {
      Title => 'Second section',
      Content => 'Nothing else to write'
    }
  ]
);

print $tmplt->eval('DOC'), "\n";

πŸ¦‹ HTML generation using functional notation πŸ¦‹

The second example shows how to generate an HTML document using a functional notation, in other words, obtaining the text:

<P><B>text in bold</B><I>text in italic</I></P>

from:

P(B("text in bold"), I("text in italic"))

The functions P(), B() and I() are defined as parts of a template. The Perl expression that permits producing the content of an element is very simple, and reduces to:

join '', @_

The content to be evaluated is the same regardless of the tag and can therefore be placed within a variable. We therefore obtain the following template:

my $ELT_CONTENT = q!%%join '', @_%%!;
my $HTML_T1 = new Parse::Template(
     'DOC' => '%%P(B("text in bold"), I("text in italic"))%%',
     'P'   => qq!<P>$ELT_CONTENT</P>!,
     'B'   => qq!<B>$ELT_CONTENT</B>!,
     'I'   => qq!<I>$ELT_CONTENT</I>!,
    );
print $HTML_T1->eval('DOC'), "\n";

We can go further by making use of the $part variable, which is defined by default in the environment of evaluation of the template:

my $ELT_CONTENT = q!%%"<$part>" . join('', @_) . "</$part>"%%!;
my $HTML_T2 = new Parse::Template(
     'DOC' => '%%P(B("text in bold"), I("text in italic"))%%',
     'P'   => qq!$ELT_CONTENT!,
     'B'   => qq!$ELT_CONTENT!,
     'I'   => qq!$ELT_CONTENT!,
    );
print $HTML_T2->eval('DOC'), "\n";

Let's look at another step which automates the production of expressions from the list of HTML tags which are of interest to us:

my $DOC = q!P(B("text in bold"), I("text in italic"))!;
my $ELT_CONTENT = q!%%"<$part>" . join('', @_) . "</$part>"%%!;
my $HTML_T3 = new Parse::Template(
     'DOC' => qq!%%$DOC%%!,
     map { $_ => $ELT_CONTENT } qw(P B I)
    );
print $HTML_T3->eval('DOC'), "\n";

To benefit from the possibility of using the template parts as procedures, we can inherit from the generated template class:

use Parse::Template;
my $ELT_CONTENT = q!%%"<$part>" . join('', @_) . "</$part>"%%!;
my $G = new Parse::Template(
     map { $_ => $ELT_CONTENT } qw(H1 B I)
    );
@main::ISA = ref($G);
*AUTOLOAD = \&Parse::Template::AUTOLOAD;
print H1(B("text in bold"), I("text in italic"));

The reference to Parse::Template::AUTOLOAD avoids the warning message:

Use of inherited AUTOLOAD for non-method %s() is deprecated

Not very elegant. 😭


πŸ’œ HTML generation by method call πŸ’œ

With a slight transformation it is possible to use a method-invocation notation:

my $ELT_CONTENT = q!%%shift(@_); "<$part>" . join('', @_) . "</$part>"%%!;
my $HTML_T4 = new Parse::Template(
     map { $_ => $ELT_CONTENT } qw(P B I)
    );
print $HTML_T4->P(
                  $HTML_T4->B("text in bold"),
                  $HTML_T4->I("text in italic")
                 ), "\n";

The shift(@_) permits getting rid of the template object, which we don't need within the expression. bye bestie πŸ‘‹


πŸŽ€ Inheritance of parts πŸŽ€

In the following example the child template $C inherits the parts defined in its parent template $A:

my %ancestor =
  (
   'TOP' => q!%%"Use the $part model and -> " . CHILD()%%!,
   'ANCESTOR' => q!ANCESTOR %%"'$part' part\n"%%!,
  );

my %child =
  (
   'CHILD' => q!CHILD %%"'$part' part"%% -> %%ANCESTOR() . "\n"%%!,
  );
my $A = new Parse::Template (%ancestor);
my $C = $A->new(%child);
print $C->TOP();

The part <TOP> defined in $A can be called directly from $C, that derives from $A. it's giving family tree, and honestly? obsessed. 🌳✨


⭐ Other examples ⭐

Parse::Template was initially created to serve as a code generator for the Parse::Lex class. You will find other examples of its use in the classes Parse::Lex, Parse::CLex and Parse::Token.


πŸ’– NOTES CONCERNING THE CURRENT VERSION πŸ’–

I would be very interested to receive your comments and suggestions. fr fr, slide into the author's inbox. πŸ“¬


πŸ’€ BUGS πŸ’€

Instances are not destroyed. Therefore, do not use this class to create a large number of instances.

bestie this is the real tea: no destructor, so the instances just... linger. make a million of them and you will absolutely feel it. πŸ‘»

πŸ‘‘ AUTHOR πŸ‘‘

Philippe Verdret (with translation of documentation into English by Ocrat)


Copyright (c) 1995-2001 Philippe Verdret. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


and that's a wrap on the whole page, gorgeous 🫢 this one shipped as perl v5.42.0, dated 2025-07-25, and it's filed under Parse::Template(3) β€” go forth and template slay, periodt. πŸ’…βœ¨

πŸ“¦ where this page comes from