Mojolicious模板渲染(八)

一、布局

大多数情况下,当使用ep模板时,我们通过布局将生成的内容包装在HTML框架中。

use Mojolicious::Lite;
 
get '/' => {template => 'foo/bar'};
 
app->start;
__DATA__
 
@@ foo/bar.html.ep
% layout 'mylayout';
                          #这是声明使用特定的模板
Hello World!
 
@@ layouts/mylayout.html.ep
                   #这是模板
<!DOCTYPE html>
<html>
  <head><title>MyApp</title></head>
  <body><%= content %></body>
                 #这是模板中默认的代码块存放区域
</html>

如上例所示,我们仅需要调用Mojolicious::Plugin::DefaultHelpers的layout helper来选择合适的模板,Mojolicious::Plugin::DefaultHelpers的content helper将会显示用于结果的展示工作。

layout helper中我们可以使用stash关键字的传递变量:

use Mojolicious::Lite;
 
get '/' => {template => 'foo/bar'};
 
app->start;
__DATA__
 
@@ foo/bar.html.ep
% layout 'mylayout', title => 'Hi there';
Hello World!
 
@@ layouts/mylayout.html.ep
<!DOCTYPE html>
<html>
  <head><title><%= $title %></title></head>
  <body><%= content %></body>
</html>

我们也可以不在模板中调用helper,使用stash关键字layout,或者在Mojolicious::Controller的render方法中使用layout参数:

$c->render(template => 'mytemplate', layout => 'mylayout');

如果我们的大多数模板都会使用同一个模板,可以把此模板设置为默认值:

$app->defaults(layout => 'mylayout');

Mojolicious::Controller中的render_to_string方法可以使用布局,仅需要使用layout参数:

my $html = $c->render_to_string('reminder', layout => 'mail');

标签