# perldoc > Text::Template

yaml
---
type: CommandReference
command: Text::Template
mode: perldoc
section: ""
source: perldoc
---

## Quick Reference

- `Text::Template->new(TYPE => 'FILE', SOURCE => $filename)` — create template from file
- `Text::Template->new(TYPE => 'STRING', SOURCE => '...')` — create template from string
- `$template->fill_in(PACKAGE => 'Pkg')` — evaluate template in package Pkg
- `$template->fill_in(HASH => \%vars)` — pass variables via hash
- `$template->fill_in(BROKEN => \&callback)` — handle errors with custom function
- `$template->fill_in(SAFE => $compartment)` — restrict operations via Safe compartment
- `$template->fill_in(OUTPUT => \*FH)` — print directly to filehandle
- `fill_in_string($string, OPTIONS)` — quick fill from string (import `'fill_in_string'`)

## Name

Expand template text with embedded Perl

## Synopsis

perl
use Text::Template;

# Construct template object
$template = Text::Template->new(TYPE => 'FILE', SOURCE => 'file.tmpl');
$template = Text::Template->new(TYPE => 'STRING', SOURCE => '...');
$template = Text::Template->new(TYPE => 'ARRAY', SOURCE => [ ... ]);
$template = Text::Template->new(TYPE => 'FILEHANDLE', SOURCE => \*FH);

# Optional options for new()
$template = Text::Template->new(
    TYPE       => 'FILE',
    SOURCE     => 'file.tmpl',
    ENCODING   => 'UTF-8',
    UNTAINT    => 1,
    DELIMITERS => [ '\[%', '%\]' ],
    PREPEND    => q{use strict;},
    BROKEN     => \&callback,
);

# Fill template
$text = $template->fill_in(PACKAGE => 'Pkg');
$text = $template->fill_in(HASH => \%vars);
$text = $template->fill_in(HASH => [\%defaults, \%user_input]);
$text = $template->fill_in(BROKEN => \&my_broken, BROKEN_ARG => \$error);
$text = $template->fill_in(SAFE => $compartment);
$template->fill_in(OUTPUT => \*STDOUT);
$text = $template->fill_in(DELIMITERS => [ '\[%', '%\]' ]);
$text = $template->fill_in(PREPEND => q{use strict 'vars';});
$text = $template->fill_in(FILENAME => 'foo.txt');

# Convenience functions
use Text::Template 'fill_in_string';
$text = fill_in_string(<<'EOM', HASH => \%vars);
Dear {$name},
...
EOM

use Text::Template 'fill_in_file';
$text = fill_in_file($filename, HASH => \%vars);

# Global prepend
Text::Template->always_prepend(q{use strict;});
## Options

### Constructor (`new`)

- `TYPE` — source type: `'FILE'`, `'STRING'`, `'ARRAY'`, `'FILEHANDLE'` (default `'FILE'`)
- `SOURCE` — filename, string, array ref, or filehandle (required)
- `DELIMITERS` — reference to array of two strings for custom delimiters (default `['{', '}']`)
- `ENCODING` — decode file from encoding (e.g., `'UTF-8'`) using Encode module
- `UNTAINT` — disable taint checks on template code from file (value `1`)
- `PREPEND` — prepend Perl code to each program fragment
- `BROKEN` — default error handler for all `fill_in` calls on this template

### `fill_in` Options

- `PACKAGE` — evaluate fragments in given package (default: caller's package)
- `HASH` — reference to hash (or array of hashes) mapping variable names to values
  - String/number → `$key`
  - Array ref → `@key`
  - Hash ref → `%key`
  - Other ref → `$key` (aliased)
- `BROKEN` — reference to error handler function; receives hash with `text`, `error`, `lineno`, `arg`
- `BROKEN_ARG` — value passed to `BROKEN` function as `$args{arg}`
- `FILENAME` — reported filename in error messages (e.g., `'foo.txt'`)
- `SAFE` — Safe compartment object for restricted evaluation
- `OUTPUT` — filehandle to print output directly (instead of returning string)
- `PREPEND` — override prepended code for this call
- `DELIMITERS` — override delimiters for this call
- `STRICT` — if `1` and `HASH` given, implies `use strict;` (alternative to `PREPEND`)

### Class Methods

- `Text::Template->always_prepend($code)` — prepend code to every program fragment for all templates

### Convenience Functions

- `fill_in_string($template_text, OPTIONS)` — fill template from string (import `'fill_in_string'`)
- `fill_in_file($filename, OPTIONS)` — fill template from file (import `'fill_in_file'`)

## Examples

**Basic form letter** (template file `formletter.tmpl`):
Dear {$title} {$lastname},

It has come to our attention that you are delinquent in your
{$monthname[$last_paid_month]} payment.  Please remit
${sprintf("%.2f", $amount)} immediately, or your patellae may
be needlessly endangered.

                Love,

                Mark "Vizopteryx" Dominus
Program:
perl
use Text::Template;
my $template = Text::Template->new(SOURCE => 'formletter.tmpl')
    or die "Couldn't construct template: $Text::Template::ERROR";
my @monthname = qw(January February ...);
my %vars = (
    title           => 'Mr.',
    lastname        => 'Smith',
    last_paid_month => 1,
    amount          => 392.12,
    monthname       => \@monthname,
);
my $result = $template->fill_in(HASH => \%vars)
    or die "Couldn't fill in template: $Text::Template::ERROR";
print $result;
**Using $OUT to build output**:
perl
# Template:
Here is a list of things:
{ foreach $i (@items) {
    $OUT .= "  * $i\n";
  }
}
**Handling errors with BROKEN**:
perl
my $error = '';
sub my_broken {
    my %args = @_;
    my $err_ref = $args{arg};
    $$err_ref = "Some error message";
    return undef;
}
$template->fill_in(BROKEN => \&my_broken, BROKEN_ARG => \$error);
if ($error) { die "It didn't work: $error" }
**Including files**:
perl
# In template:
{ Text::Template::_load_text('header.html') }
# Or with alias:
*Q::include = \&Text::Template::_load_text;
# Then in template: { include('header.html') }
**JavaScript compatibility**:
perl
# Instead of raw braces, use:
{ q{if (br== "n3") {
    // etc.
  }}
}
## See Also

- [Text::Template::Preprocess](https://metacpan.org/pod/Text::Template::Preprocess) — automatic preprocessing of program fragments
- [Safe](https://metacpan.org/pod/Safe) — restricted execution compartments
- [Encode](https://metacpan.org/pod/Encode) — character encoding support
- [perlsec](https://metacpan.org/pod/perlsec) — Perl security (taint mode)
- [CGI](https://metacpan.org/pod/CGI) — sticky widgets for forms

## Exit Codes

Not documented. Module returns `undef` on failure and sets `$Text::Template::ERROR`.