Mojo::Template
简介
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是一个简约、快速、纯Perl-ish的模板引擎,专为在大项目中出现的小型任务而设计。像预处理一个配置文件,从heredocs生成文本等。有关Mojolicious中渲染器的更多内容你可以参考Mojolicious::Guides::Rendering。
语法
在所有模板解析的过程中默认启用strict、warning和perl5.10特性。
<% 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
改变默认转义行为
在默认情况下转义auto_escape是关闭的。渲染方式如下:
<%= Perl expression, replaced with result %>
<%== Perl expression, replaced with XML escaped result %>
如果设置 auto_escape 为true,对转义行的渲染方式也将改变:
<%= Perl expression, replaced with XML escaped result %>
<%== Perl expression, replaced with result %>
Mojo::ByteStream对象永远都不会被转义。
% use Mojo::ByteStream 'b';
<%= b('<div>excluded!</div>') %>
空白修剪
标签两边的空白字符可以通过在标签的末尾添加一个等号来修剪.
<% for (1 .. 3) { %>
<%= 'Trim all whitespace characters around this expression' =%>
<% } %>
换行符可以通过在行尾加一个反斜杠进行转义(反斜杠后不能有任何字符):
This is <%= 1 + 1 %> a\
single line
如果需要生成模板,可以在反斜杠前面再加一个反斜杠来转义后面的反斜杠。
This will <%= 1 + 1 %> result\\
in multiple\\
lines
在模板中,如果没有遇到反斜杠转义,则所有非模板末尾的空行都将被保留。也就是说所有被反斜杠转义换行符都将被忽略,模板末尾的空行也将被忽略。
There is <%= 1 + 1 %> no newline at the end here\
在模板中定义代码块(函数)
可以在模板中使用begin和end关键字来定义代码块。因为这两个单词只是模板中标签的组成部分,而非perl的关键字,所以在begin之前需要有一个换行,而在end之前需要有一个换行。
<% my $block = begin %>
<% my $name = shift; =%>
Hello <%= $name %>.
<% end %>
<%= $block->('Baerbel') %>
<%= $block->('Wolfgang') %>
在单行的perl模板中也可以有缩进,使用方式如下:
% my $block = begin
% my $name = shift;
Hello <%= $name %>.
% end
%= $block->('Baerbel')
%= $block->('Wolfgang')
访问参数 @_
Mojo::Template模板被编译成一个Perl了程序,所以你可以通过@_来访问参数列表。
% my ($foo, $bar) = @_;
% my $x = shift;
test 123 <%= $foo %>
模板中的异常处理
对于模板中Perl代码的编译调试,如果出现错误Mojo::Template会返回一个Mojo::Exception对象,该对象中保存有出错时的上下文信息。如下所示:
Bareword "xx" not allowed while "strict subs" in use at template line 4.
2: </head>
3: <body>
4: % my $i = 2; xx
5: %= $i * 2
6: </body>
属性
Mojo::Template中有如下属性。
auto_escape
my $bool = $mt->auto_escape;
$mt = $mt->auto_escape($bool);
激活自动转义,会使模板中的转义语法发生转变。
# "<html>"
Mojo::Template->new(auto_escape => 1)->render("<%= '<html>' %>");
append
my $code = $mt->append;
$mt = $mt->append('warn "Processed template"');
将Perl代码附加到编译的模板中,需要注意:此代码不应该包括换行符,否则错误消息中的等号可能会出错。
capture_end
my $end = $mt->capture_end;
$mt = $mt->capture_end('end');
块结束的关键字,默认为: end 。
<% my $block = begin %>
Some data!
<% end %>
capture_start
my $start = $mt->capture_start;
$mt = $mt->capture_start('begin');
块开始的关键字,默认为:begin 。
<% my $block = begin %>
Some data!
<% end %>
code
my $code = $mt->code;
$mt = $mt->code($code);
适用于模板的perl代码。
comment_mark
my $mark = $mt->comment_mark;
$mt = $mt->comment_mark('#');
注释的开始字符,默认为 #。
<%# This is a comment %>
编译
my $compiled = $mt->compiled;
$mt = $mt->compiled($compiled);
编译模板代码(如果可用)。
encoding
my $encoding = $mt->encoding;
$mt = $mt->encoding('UTF-8');
用于模板文件编码的编码格式,默认为UTF-8。
escape
my $cb = $mt->escape;
$mt = $mt->escape(sub {...});
用于转义“转义表达式结果”的回调函数。默认为Mojo::Util::xml_escape。
$mt->escape(sub {
my $str = shift;
return reverse $str;
});
escape_mark
my $mark = $mt->escape_mark;
$mt = $mt->escape_mark('=');
转义表达式开始的字符,默认为: = 。
<%== $foo %>
expression_mark
my $mark = $mt->expression_mark;
$mt = $mt->expression_mark('=');
表达式开始的字符,默认为 = 。
<%= $foo %>
line_start
my $start = $mt->line_start;
$mt = $mt->line_start('%');
表示单行代码开始的字符,默认为 %。
% $foo = 23;
name
my $name = $mt->name;
$mt = $mt->name('foo.mt');
目前正在处理的模板名称,默认为template。注:此值不能包含引号和换行,否则错误消息中给出的信息可能会不正确。
namespace
my $namespace = $mt->namespace;
$mt = $mt->namespace('main');
用于编译模板的命名空间,默认为Mojo::Template::SandBox。注:命名空间中的函数和全局变量将会在各个模块间共享,因为同个命名空间下的函数和变量在程序运行期间不会被清除。
prepend
my $code = $mt->prepend;
$mt = $mt->prepend('my $self = shift;');
将Perl代码预编译成模板。注:此代码能够包含换行,否则错误消息中的行号会出错。
replace_mark
my $mark = $mt->replace_mark;
$mt = $mt->replace_mark('%');
用于转义标记或行的开头字符,默认为“%”。
<%% my $foo = 23; %>
tag_start
my $start = $mt->tag_start;
$mt = $mt->tag_start('<%');
标记开始字符,默认为<%
.
<% $foo = 23; %>
tag_end
my $start = $mt->tag_start;
$mt = $mt->tag_start('<%');
标记结束的字符,默认为:%>
<%= $foo %>
tree
my $tree = $mt->tree;
$mt = $mt->tree([['text', 'foo'], ['line']]);
解析后的模板树。注:一般让Mojo::Template对象自己维护就行了,如果用户要手动维护那就得非常小心了。
trim_mark
my $mark = $mt->trim_mark;
$mt = $mt->trim_mark('-');
启用自动空白修剪的字符。默认为=
。
<%= $foo =%>
unparsed
my $unparsed = $mt->unparsed;
$mt = $mt->unparsed('<%= 1 + 1 %>');
未解析的原始模板。
vars
my $bool = $mt->vars;
$mt = $mt->vars($bool);
是否启用替换值的列表,如果为真,则可以使用带有命名变量的哈希引用将数据传递给模板。
方法
Mojo::Template继承Mojo::Base中的所有方法,并实现以下方法。
parse
$mt = $mt->parse('<%= 1 + 1 %>');
将原始模板解析成 树开结构的数据。
process
my $output = $mt->process;
my $output = $mt->process(@args);
my $output = $mt->process({foo => 'bar'});
处理先前解析的模板并返回结果,如果渲染失败,则返回 Mojo::Exception对象。
# 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');
render
my $output = $mt->render('<%= 1 + 1 %>');
my $output = $mt->render('<%= shift() + shift() %>', @args);
my $output = $mt->render('<%= $foo %>', {foo => 'bar'});
渲染模板并返回结果,如果渲染失败,则返回Mojo::Exception对象。
# 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'});
render_file
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'});
与 render 方法功能相同,但render_file是从一个文件中读取模板并渲染。
DEBUGGING
您可以设置环境变量MOJO_TEMPLATE_DEBUG,得以从STDERR中获取一些高级诊断信息。
MOJO_TEMPLATE_DEBUG=1