Mojolicious模板渲染(十)
一、增加helpers
在代码开发过程中,我们应该始终设计、保持代码的可重用性。helper便是代码可重用性的一种良好的实现方式:
use Mojolicious::Lite -signatures;
helper debug => sub ($c, $str) {
#helper定义
$c->app->log->debug($str);
};
get '/' => sub ($c) {
$c->debug('Hello from an action!');
#helper的调用方式
} => 'index';
app->start;
__DATA__
@@ index.html.ep
% debug 'Hello from a template!';
helper还可以接受模板块作为最后一个参数,例如我们可以轻松地使用tag helper和过滤器helper。将helper结果包装为Mojo::ByteStream对象可以防止意外的双转义。
use Mojolicious::Lite -signatures;
use Mojo::ByteStream;
helper trim_newline => sub ($c, $block) {
#定义了trim_newline
my $result = $block->();
$result =~ s/\n//g;
return Mojo::ByteStream->new($result);
};
get '/' => 'index';
app->start;
__DATA__
@@ index.html.ep
%= trim_newline begin
#begin end间的代码块将作为参数$block的值传递
Some text.
%= 1 + 1
More text.
% end
和stash值类似,我们可以使用类似myapp.*前缀的语法来避免helper像函数一样暴露在模板中,同时当我们的应用壮大时也可以将前缀发展为命名空间。每个前缀都会自动成为一个helper,它返回一个包含当前控制器对象的代理对象,我们可以在调用这个嵌套的helper。
use Mojolicious::Lite -signatures;
helper 'cache_control.no_caching' => sub ($c) { $c->res->headers->cache_control('private, max-age=0, no-cache') };
helper 'cache_control.five_minutes' => sub ($c) { $c->res->headers->cache_control('public, max-age=300') };
get '/news' => sub ($c) {
$c->cache_control->no_caching;
$c->render(text => 'Always up to date.');
};
get '/some_older_story' => sub ($c) {
$c->cache_control->five_minutes;
$c->render(text => 'This one can be cached for a bit.');
};
app->start;
虽然也可以重新定义helper,但应该非常小心地这样做,以避免冲突。