Mojo::Template - Perl-ish templates
use Mojo::Template;
# Use Perl modules
my $mt = Mojo::Template->new;
say $mt->render(<<'EOF');
% use Time::Piece;
<div>
% my $now = localtime;
Time: <%= $now->hms %>
</div>
EOF
# Render with arguments
say $mt->render(<<'EOF', [1 .. 13], 'Hello World!');
% my ($numbers, $title) = @_;
<div>
<h1><%= $title %></h1>
% for my $i (@$numbers) {
Test <%= $i %>
% }
</div>
EOF
# Render with named variables
say $mt->vars(1)->render(<<'EOF', {title => 'Hello World!'});
<div>
<h1><%= $title %></h1>
%= 5 + 5
</div>
EOF
Mojo::Template is a minimalistic, fast, and very Perl-ish template engine, designed specifically for all those small tasks that come up during big projects. Like preprocessing a configuration file, generating text from heredocs and stuff like that.
See Mojolicious::Guides::Rendering for information on how to generate content with the Mojolicious renderer.
For all templates strict, warnings, utf8 and Perl 5.16 features are automatically enabled.
<% Perl code %>
<%= Perl expression, replaced with result %>
<%== Perl expression, replaced with XML escaped result %>
<%# Comment, useful for debugging %>
<%% Replaced with "<%", useful for generating templates %>
% Perl code line, treated as "<% line =%>" (explained later)
%= Perl expression line, treated as "<%= line %>"
%== Perl expression line, treated as "<%== line %>"
%# Comment line, useful for debugging
%% Replaced with "%", useful for generating templates
Escaping behavior can be reversed with the "auto_escape" attribute, this is the default in Mojolicious .ep
templates, for example.
<%= Perl expression, replaced with XML escaped result %>
<%== Perl expression, replaced with result %>
Mojo::ByteStream objects are always excluded from automatic escaping.
% use Mojo::ByteStream qw(b);
<%= b('<div>excluded!</div>') %>
Whitespace characters around tags can be trimmed by adding an additional equal sign to the end of a tag.
<% for (1 .. 3) { %>
<%= 'Trim all whitespace characters around this expression' =%>
<% } %>
Newline characters can be escaped with a backslash.
This is <%= 1 + 1 %> a\
single line
And a backslash in front of a newline character can be escaped with another backslash.
This will <%= 1 + 1 %> result\\
in multiple\\
lines
A newline character gets appended automatically to every template, unless the last character is a backslash. And empty lines at the end of a template are ignored.
There is <%= 1 + 1 %> no newline at the end here\
You can capture whole template blocks for reuse later with the begin
and end
keywords. Just be aware that both keywords are part of the surrounding tag and not actual Perl code, so there can only be whitespace after begin
and before end
.
<% my $block = begin %>
<% my $name = shift; =%>
Hello <%= $name %>.
<% end %>
<%= $block->('Baerbel') %>
<%= $block->('Wolfgang') %>
Perl lines can also be indented freely.
% my $block = begin
% my $name = shift;
Hello <%= $name %>.
% end
%= $block->('Baerbel')
%= $block->('Wolfgang')
Mojo::Template templates get compiled to a Perl subroutine, that means you can access arguments simply via @_
.
% my ($foo, $bar) = @_;
% my $x = shift;
test 123 <%= $foo %>
The compilation of templates to Perl code can make debugging a bit tricky, but Mojo::Template will return Mojo::Exception objects that stringify to error messages with context.
Bareword "xx" not allowed while "strict subs" in use at template line 4.
Context:
2: </head>
3: <body>
4: % my $i = 2; xx
5: %= $i * 2
6: </body>
Traceback (most recent call first):
File "template", line 4, in "Mojo::Template::Sandbox"
File "path/to/Mojo/Template.pm", line 123, in "Mojo::Template"
File "path/to/myapp.pl", line 123, in "main"
Mojo::Template implements the following attributes.
my $bool = $mt->auto_escape;
$mt = $mt->auto_escape($bool);
Activate automatic escaping.
# "<html>"
Mojo::Template->new(auto_escape => 1)->render("<%= '<html>' %>");
my $code = $mt->append;
$mt = $mt->append('warn "Processed template"');
Append Perl code to compiled template. Note that this code should not contain newline characters, or line numbers in error messages might end up being wrong.
my $end = $mt->capture_end;
$mt = $mt->capture_end('end');
Keyword indicating the end of a capture block, defaults to end
.
<% my $block = begin %>
Some data!
<% end %>
my $start = $mt->capture_start;
$mt = $mt->capture_start('begin');
Keyword indicating the start of a capture block, defaults to begin
.
<% my $block = begin %>
Some data!
<% end %>
my $code = $mt->code;
$mt = $mt->code($code);
Perl code for template if available.
my $mark = $mt->comment_mark;
$mt = $mt->comment_mark('#');
Character indicating the start of a comment, defaults to #
.
<%# This is a comment %>
my $compiled = $mt->compiled;
$mt = $mt->compiled($compiled);
Compiled template code if available.
my $encoding = $mt->encoding;
$mt = $mt->encoding('UTF-8');
Encoding used for template files, defaults to UTF-8
.
my $cb = $mt->escape;
$mt = $mt->escape(sub {...});
A callback used to escape the results of escaped expressions, defaults to "xml_escape" in Mojo::Util.
$mt->escape(sub ($str) { return reverse $str });
my $mark = $mt->escape_mark;
$mt = $mt->escape_mark('=');
Character indicating the start of an escaped expression, defaults to =
.
<%== $foo %>
my $mark = $mt->expression_mark;
$mt = $mt->expression_mark('=');
Character indicating the start of an expression, defaults to =
.
<%= $foo %>
my $start = $mt->line_start;
$mt = $mt->line_start('%');
Character indicating the start of a code line, defaults to %
.
% $foo = 23;
my $name = $mt->name;
$mt = $mt->name('foo.mt');
Name of template currently being processed, defaults to template
. Note that this value should not contain quotes or newline characters, or error messages might end up being wrong.
my $namespace = $mt->namespace;
$mt = $mt->namespace('main');
Namespace used to compile templates, defaults to Mojo::Template::Sandbox
. Note that namespaces should only be shared very carefully between templates, since functions and global variables will not be cleared automatically.
my $code = $mt->prepend;
$mt = $mt->prepend('my $self = shift;');
Prepend Perl code to compiled template. Note that this code should not contain newline characters, or line numbers in error messages might end up being wrong.
my $mark = $mt->replace_mark;
$mt = $mt->replace_mark('%');
Character used for escaping the start of a tag or line, defaults to %
.
<%% my $foo = 23; %>
my $start = $mt->tag_start;
$mt = $mt->tag_start('<%');
Characters indicating the start of a tag, defaults to <%
.
<% $foo = 23; %>
my $end = $mt->tag_end;
$mt = $mt->tag_end('%>');
Characters indicating the end of a tag, defaults to %>
.
<%= $foo %>
my $tree = $mt->tree;
$mt = $mt->tree([['text', 'foo'], ['line']]);
Template in parsed form if available. Note that this structure should only be used very carefully since it is very dynamic.
my $mark = $mt->trim_mark;
$mt = $mt->trim_mark('-');
Character activating automatic whitespace trimming, defaults to =
.
<%= $foo =%>
my $unparsed = $mt->unparsed;
$mt = $mt->unparsed('<%= 1 + 1 %>');
Raw unparsed template if available.
my $bool = $mt->vars;
$mt = $mt->vars($bool);
Instead of a list of values, use a hash reference with named variables to pass data to templates.
# "works!"
Mojo::Template->new(vars => 1)->render('<%= $test %>!', {test => 'works'});
Mojo::Template inherits all methods from Mojo::Base and implements the following new ones.
$mt = $mt->parse('<%= 1 + 1 %>');
Parse template into "tree".
my $output = $mt->process;
my $output = $mt->process(@args);
my $output = $mt->process({foo => 'bar'});
Process previously parsed template and return the result, or a Mojo::Exception object if rendering failed.
# Parse and process
say Mojo::Template->new->parse('Hello <%= $_[0] %>')->process('Bender');
# Reuse template (for much better performance)
my $mt = Mojo::Template->new;
say $mt->render('Hello <%= $_[0] %>!', 'Bender');
say $mt->process('Fry');
say $mt->process('Leela');
my $output = $mt->render('<%= 1 + 1 %>');
my $output = $mt->render('<%= shift() + shift() %>', @args);
my $output = $mt->render('<%= $foo %>', {foo => 'bar'});
Render template and return the result, or a Mojo::Exception object if rendering failed.
# Longer version
my $output = $mt->parse('<%= 1 + 1 %>')->process;
# Render with arguments
say Mojo::Template->new->render('<%= $_[0] %>', 'bar');
# Render with named variables
say Mojo::Template->new(vars => 1)->render('<%= $foo %>', {foo => 'bar'});
my $output = $mt->render_file('/tmp/foo.mt');
my $output = $mt->render_file('/tmp/foo.mt', @args);
my $output = $mt->render_file('/tmp/bar.mt', {foo => 'bar'});
Same as "render", but renders a template file.
You can set the MOJO_TEMPLATE_DEBUG
environment variable to get some advanced diagnostics information printed to STDERR
.
MOJO_TEMPLATE_DEBUG=1