Mojolicious模板渲染(十九)

一、添加我们的模板系统

如果我们不喜欢Mojolicious::Plugin::EPRenderer模块提供的ep模板系统,我们可以自己创建一个。

关于定义一个属于我们自己的模板系统,我们需要做的是在register定义插件时,使用Mojolicious::Renderer模块的add_handler方法建立一个新的句柄:

package Mojolicious::Plugin::MyRenderer;
use Mojo::Base 'Mojolicious::Plugin', -signatures;
 
sub register ($self, $app, $conf) {
 
  # 增加 "mine" 句柄
  $app->renderer->add_handler(mine => sub ($renderer, $c, $output, $options) {
 
    # 检查一次性使用的内联模板
    my $inline_template = $options->{inline};
 
    # 在“templates”目录中检查是否有合适的模板
    my $template_path = $renderer->template_path($options);
 
    # 在DATA部分中检查合适的模板
    my $data_template = $renderer->get_data_template($options);
 
    # 这部分取决于你和你的模板系统 :)
    ...
 
    # 将呈现的结果传回渲染器
    $$output = 'Hello World!';
 
    # 或者在出错时die
    die 'Something went wrong with the template';
  });
}
 
1;

如果用户提供了内联模板,那么它将与选项一起传递。我们可以通过Mojolicious::Renderer模板的template_path查找templates目录,或Mojolicious::Renderer的”get_data_template” 方法在DATA部分查找:

use Mojolicious::Lite;
 
plugin 'MyRenderer';
 
# 呈现内联模板
get '/inline' => {inline => '...', handler => 'mine'};
 
# 从DATA部分呈现模板
get '/data' => {template => 'test'};
 
app->start;
__DATA__
 
@@ test.html.mine
...

标签