Mojolicious模板渲染(九)
一、Partial templates
这个名词我也没想好怎么翻译。这是一种特殊的模板,确切说是一种html代码块,可以插入到其他模板中的重复使用。我们使用Mojolicious::Plugin::DefaultHelpers中include helper调用这个html代码块模板:
use Mojolicious::Lite;
get '/' => {template => 'foo/bar'};
app->start;
__DATA__
@@ foo/bar.html.ep
<!DOCTYPE html>
<html>
%= include '_header', title => 'Howdy' #这是include helper的使用方法。
<body>Bar</body>
</html>
@@ _header.html.ep #这个即是Partial templates
<head><title><%= $title %></title></head>
我们可以随意命名部分模板,但前面的下划线是常用的命名约定。
二、可重用模板模块
重复并不有趣,这就是为什么我们可以在ep中构建可重用的模板块,这些模板块的工作方式非常类似于普通的Perl函数(确切的讲,有点类似于闭包),我们把begin赋值给模板的名字,而在begin和end之间设计我们重用的模板块:
use Mojolicious::Lite;
get '/' => 'welcome';
app->start;
__DATA__
@@ welcome.html.ep
<% my $block = begin %> #此处开始为可重用模板块的声明
% my $name = shift;
Hello <%= $name %>.
<% end %>
<%= $block->('Wolfgang') %> #下面两行为可重用模板块的调用方式
<%= $block->('Baerbel') %>
如果把上面这个模板转化为纯Perl语言代码,如下:
my $output = '';
my $block = sub ($name) {
my $output = '';
$output .= 'Hello ';
$output .= xml_escape scalar + $name;
$output .= '.';
return Mojo::ByteStream->new($output);
};
$output .= xml_escape scalar + $block->('Wolfgang');
$output .= xml_escape scalar + $block->('Baerbel');
return $output;
虽然模板块不能在模板之间共享,但它们最常用来将模板的某些部分传递给helper。