Text Templates in Perl

Perl offers built-in support for creating dynamic content or showing customized output to the user with the Text::Template module. This module provides a simple way to generate text using templates.

use strict;
use warnings;
use Text::Template;
use Data::Dumper;

# We can create a new template and parse its body from a string.
# Templates are a mix of static text and expressions enclosed in
# {$...} that are used to dynamically insert content.

my $t1 = Text::Template->new(
    TYPE => 'STRING',
    SOURCE => 'Value is {$_}',
);

# By "filling in" the template we generate its text with
# specific values for its expressions.
print $t1->fill_in(HASH => { _ => "some text" });
print $t1->fill_in(HASH => { _ => 5 });
print $t1->fill_in(HASH => { _ => Dumper(["Perl", "Python", "Ruby", "PHP"]) });

# If the data is a hash we can use the {$variable} syntax to access
# its keys.

my $t2 = Text::Template->new(
    TYPE => 'STRING',
    SOURCE => 'Name: {$name}',
);

print $t2->fill_in(HASH => { name => "Jane Doe" });
print $t2->fill_in(HASH => { name => "Mickey Mouse" });

# if/else provide conditional execution for templates. A value is considered
# false if it's undefined, an empty string, 0, or an empty list.

my $t3 = Text::Template->new(
    TYPE => 'STRING',
    SOURCE => '{if $_}yes{else}no{/if}',
);

print $t3->fill_in(HASH => { _ => "not empty" }), "\n";
print $t3->fill_in(HASH => { _ => "" }), "\n";

# To loop through arrays, we can use Perl's foreach construct within
# the template.

my $t4 = Text::Template->new(
    TYPE => 'STRING',
    SOURCE => 'Range: {foreach $item (@$_) {$item } }',
);

print $t4->fill_in(HASH => { _ => ["Perl", "Python", "Ruby", "PHP"] }), "\n";

When you run this script, you should see output similar to this:

$ perl templates.pl
Value is some text
Value is 5
Value is $VAR1 = [
          'Perl',
          'Python',
          'Ruby',
          'PHP'
        ];

Name: Jane Doe
Name: Mickey Mouse
yes
no
Range: Perl Python Ruby PHP 

In this Perl version:

  1. We use the Text::Template module for templating.
  2. Template variables are enclosed in {$...} instead of {{...}}.
  3. We use fill_in method to render templates instead of Execute.
  4. Conditional statements use {if}...{else}...{/if} syntax.
  5. For looping, we use Perl’s foreach construct directly in the template.

Note that Perl’s Text::Template is more flexible than Go’s text/template in some ways, as it allows arbitrary Perl code in the templates. This can be powerful but also potentially dangerous if used with untrusted input.

查看推荐产品

Comments powered by Disqus